prettier 1.6.1 → 2.0.0.pre.rc1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (149) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +316 -293
  3. data/CONTRIBUTING.md +6 -9
  4. data/LICENSE +1 -1
  5. data/README.md +11 -12
  6. data/dist/haml/embed.js +53 -0
  7. data/dist/haml/parser.js +31 -0
  8. data/{src → dist}/haml/parser.rb +0 -0
  9. data/dist/haml/printer.js +336 -0
  10. data/dist/parser/getInfo.js +17 -0
  11. data/{src → dist}/parser/netcat.js +1 -0
  12. data/dist/parser/parseSync.js +128 -0
  13. data/dist/parser/server.rb +140 -0
  14. data/dist/plugin.js +143 -0
  15. data/dist/prettier.js +15 -0
  16. data/dist/rbs/parser.js +34 -0
  17. data/{src → dist}/rbs/parser.rb +0 -0
  18. data/dist/rbs/printer.js +517 -0
  19. data/dist/ruby/embed.js +110 -0
  20. data/dist/ruby/nodes/alias.js +59 -0
  21. data/{src → dist}/ruby/nodes/aref.js +26 -35
  22. data/dist/ruby/nodes/args.js +165 -0
  23. data/dist/ruby/nodes/arrays.js +126 -0
  24. data/dist/ruby/nodes/assign.js +41 -0
  25. data/dist/ruby/nodes/blocks.js +68 -0
  26. data/dist/ruby/nodes/calls.js +220 -0
  27. data/dist/ruby/nodes/case.js +50 -0
  28. data/dist/ruby/nodes/class.js +54 -0
  29. data/dist/ruby/nodes/commands.js +124 -0
  30. data/dist/ruby/nodes/conditionals.js +242 -0
  31. data/dist/ruby/nodes/constants.js +38 -0
  32. data/dist/ruby/nodes/flow.js +66 -0
  33. data/dist/ruby/nodes/hashes.js +130 -0
  34. data/dist/ruby/nodes/heredocs.js +30 -0
  35. data/dist/ruby/nodes/hooks.js +35 -0
  36. data/dist/ruby/nodes/ints.js +27 -0
  37. data/dist/ruby/nodes/lambdas.js +69 -0
  38. data/dist/ruby/nodes/loops.js +73 -0
  39. data/dist/ruby/nodes/massign.js +73 -0
  40. data/dist/ruby/nodes/methods.js +70 -0
  41. data/dist/ruby/nodes/operators.js +70 -0
  42. data/dist/ruby/nodes/params.js +89 -0
  43. data/dist/ruby/nodes/patterns.js +109 -0
  44. data/dist/ruby/nodes/regexp.js +45 -0
  45. data/dist/ruby/nodes/rescue.js +82 -0
  46. data/dist/ruby/nodes/return.js +75 -0
  47. data/dist/ruby/nodes/statements.js +111 -0
  48. data/dist/ruby/nodes/strings.js +218 -0
  49. data/dist/ruby/nodes/super.js +30 -0
  50. data/dist/ruby/nodes/undef.js +26 -0
  51. data/dist/ruby/nodes.js +151 -0
  52. data/dist/ruby/parser.js +34 -0
  53. data/{src → dist}/ruby/parser.rb +1215 -252
  54. data/dist/ruby/printer.js +125 -0
  55. data/dist/ruby/toProc.js +93 -0
  56. data/dist/types/haml.js +4 -0
  57. data/dist/types/plugin.js +3 -0
  58. data/dist/types/rbs.js +4 -0
  59. data/dist/types/ruby.js +4 -0
  60. data/dist/types/utils.js +2 -0
  61. data/dist/types.js +30 -0
  62. data/dist/utils/containsAssignment.js +15 -0
  63. data/dist/utils/getTrailingComma.js +6 -0
  64. data/dist/utils/hasAncestor.js +15 -0
  65. data/{src → dist}/utils/inlineEnsureParens.js +16 -17
  66. data/dist/utils/isEmptyBodyStmt.js +10 -0
  67. data/dist/utils/isEmptyStmts.js +10 -0
  68. data/dist/utils/literal.js +8 -0
  69. data/dist/utils/literallineWithoutBreakParent.js +8 -0
  70. data/dist/utils/makeCall.js +13 -0
  71. data/dist/utils/noIndent.js +11 -0
  72. data/dist/utils/printEmptyCollection.js +44 -0
  73. data/dist/utils/skipAssignIndent.js +15 -0
  74. data/dist/utils.js +30 -0
  75. data/node_modules/prettier/bin-prettier.js +313 -190
  76. data/node_modules/prettier/doc.js +191 -323
  77. data/node_modules/prettier/index.js +2753 -3677
  78. data/node_modules/prettier/package.json +1 -1
  79. data/node_modules/prettier/parser-angular.js +13 -14
  80. data/node_modules/prettier/parser-babel.js +7 -7
  81. data/node_modules/prettier/parser-espree.js +7 -7
  82. data/node_modules/prettier/parser-flow.js +7 -7
  83. data/node_modules/prettier/parser-glimmer.js +1 -1
  84. data/node_modules/prettier/parser-graphql.js +1 -1
  85. data/node_modules/prettier/parser-html.js +17 -17
  86. data/node_modules/prettier/parser-markdown.js +9 -9
  87. data/node_modules/prettier/parser-meriyah.js +7 -7
  88. data/node_modules/prettier/parser-postcss.js +2 -2
  89. data/node_modules/prettier/parser-typescript.js +7 -7
  90. data/node_modules/prettier/parser-yaml.js +2 -2
  91. data/node_modules/prettier/third-party.js +143 -78
  92. data/package.json +26 -18
  93. metadata +74 -67
  94. data/src/haml/embed.js +0 -87
  95. data/src/haml/parser.js +0 -23
  96. data/src/haml/printer.js +0 -438
  97. data/src/parser/parseSync.js +0 -172
  98. data/src/parser/server.rb +0 -66
  99. data/src/plugin.js +0 -148
  100. data/src/prettier.js +0 -16
  101. data/src/rbs/parser.js +0 -37
  102. data/src/rbs/printer.js +0 -643
  103. data/src/ruby/embed.js +0 -142
  104. data/src/ruby/nodes/alias.js +0 -73
  105. data/src/ruby/nodes/args.js +0 -222
  106. data/src/ruby/nodes/arrays.js +0 -162
  107. data/src/ruby/nodes/assign.js +0 -47
  108. data/src/ruby/nodes/blocks.js +0 -90
  109. data/src/ruby/nodes/calls.js +0 -246
  110. data/src/ruby/nodes/case.js +0 -65
  111. data/src/ruby/nodes/class.js +0 -64
  112. data/src/ruby/nodes/commands.js +0 -131
  113. data/src/ruby/nodes/conditionals.js +0 -282
  114. data/src/ruby/nodes/constants.js +0 -43
  115. data/src/ruby/nodes/flow.js +0 -74
  116. data/src/ruby/nodes/hashes.js +0 -155
  117. data/src/ruby/nodes/heredocs.js +0 -36
  118. data/src/ruby/nodes/hooks.js +0 -34
  119. data/src/ruby/nodes/ints.js +0 -31
  120. data/src/ruby/nodes/lambdas.js +0 -76
  121. data/src/ruby/nodes/loops.js +0 -98
  122. data/src/ruby/nodes/massign.js +0 -98
  123. data/src/ruby/nodes/methods.js +0 -74
  124. data/src/ruby/nodes/operators.js +0 -83
  125. data/src/ruby/nodes/params.js +0 -106
  126. data/src/ruby/nodes/patterns.js +0 -157
  127. data/src/ruby/nodes/regexp.js +0 -56
  128. data/src/ruby/nodes/rescue.js +0 -101
  129. data/src/ruby/nodes/return.js +0 -94
  130. data/src/ruby/nodes/statements.js +0 -142
  131. data/src/ruby/nodes/strings.js +0 -272
  132. data/src/ruby/nodes/super.js +0 -35
  133. data/src/ruby/nodes/undef.js +0 -42
  134. data/src/ruby/nodes.js +0 -34
  135. data/src/ruby/parser.js +0 -37
  136. data/src/ruby/printer.js +0 -147
  137. data/src/ruby/toProc.js +0 -105
  138. data/src/utils/containsAssignment.js +0 -11
  139. data/src/utils/getTrailingComma.js +0 -5
  140. data/src/utils/hasAncestor.js +0 -17
  141. data/src/utils/isEmptyBodyStmt.js +0 -7
  142. data/src/utils/isEmptyStmts.js +0 -11
  143. data/src/utils/literal.js +0 -7
  144. data/src/utils/literallineWithoutBreakParent.js +0 -7
  145. data/src/utils/makeCall.js +0 -14
  146. data/src/utils/noIndent.js +0 -10
  147. data/src/utils/printEmptyCollection.js +0 -49
  148. data/src/utils/skipAssignIndent.js +0 -17
  149. data/src/utils.js +0 -13
@@ -0,0 +1,517 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const prettier_1 = __importDefault(require("../prettier"));
7
+ const { group, hardline, indent, makeString, join, line, softline } = prettier_1.default;
8
+ // For some lists of entities in the AST, the parser returns them as an unsorted
9
+ // object (presumably because Ruby hashes have implicit ordering). We do not
10
+ // have that in JavaScript, so here we sort each object by its position in the
11
+ // source string.
12
+ function getSortedKeys(object) {
13
+ return Object.keys(object).sort((left, right) => object[left].type.location.start_pos -
14
+ object[right].type.location.start_pos);
15
+ }
16
+ // In some cases, we want to just defer to whatever was in the source.
17
+ function getSource(node, opts) {
18
+ const { location } = node;
19
+ return opts.originalText.slice(location.start_pos, location.end_pos);
20
+ }
21
+ const printer = {
22
+ // This is the generic node print function, used to convert any node in the
23
+ // AST into its equivalent Doc representation.
24
+ print(path, opts, print) {
25
+ const node = path.getValue();
26
+ let doc = null;
27
+ if (node.declarations) {
28
+ // Prints out the root of the tree, which includes zero or more
29
+ // declarations.
30
+ return [
31
+ join([hardline, hardline], path.map(print, "declarations")),
32
+ hardline
33
+ ];
34
+ }
35
+ /* istanbul ignore else */
36
+ if (node.declaration) {
37
+ switch (node.declaration) {
38
+ // Prints out a type alias, which is a declaration that looks like:
39
+ // type foo = String
40
+ case "alias": {
41
+ doc = group([
42
+ "type ",
43
+ node.name,
44
+ " =",
45
+ indent(group([line, path.call(printType, "type")]))
46
+ ]);
47
+ break;
48
+ }
49
+ // Prints out a class declarations, which looks like:
50
+ // class Foo end
51
+ case "class": {
52
+ const nodePath = path;
53
+ const parts = [
54
+ "class ",
55
+ printNameAndTypeParams(nodePath, node)
56
+ ];
57
+ if (node.super_class) {
58
+ const superPath = nodePath;
59
+ parts.push(" < ", superPath.call(printNameAndArgs, "super_class"));
60
+ }
61
+ parts.push(indent(printMembers(nodePath)), hardline, "end");
62
+ doc = group(parts);
63
+ break;
64
+ }
65
+ // Prints out a constant or a global declaration, which looks like:
66
+ // Foo: String
67
+ // $foo: String
68
+ case "constant":
69
+ case "global": {
70
+ doc = group([node.name, ": ", path.call(printType, "type")]);
71
+ break;
72
+ }
73
+ // Prints out an interface declaration, which looks like:
74
+ // interface _Foo end
75
+ case "interface": {
76
+ const nodePath = path;
77
+ doc = group([
78
+ "interface ",
79
+ printNameAndTypeParams(nodePath, node),
80
+ indent(printMembers(nodePath)),
81
+ hardline,
82
+ "end"
83
+ ]);
84
+ break;
85
+ }
86
+ // Prints out a module declaration, which looks like:
87
+ // module Foo end
88
+ case "module": {
89
+ const nodePath = path;
90
+ const parts = [
91
+ "module ",
92
+ printNameAndTypeParams(nodePath, node)
93
+ ];
94
+ if (node.self_types.length > 0) {
95
+ parts.push(" : ", join(", ", nodePath.map(printNameAndArgs, "self_types")));
96
+ }
97
+ parts.push(indent(printMembers(nodePath)), hardline, "end");
98
+ doc = group(parts);
99
+ break;
100
+ }
101
+ /* istanbul ignore next */
102
+ default:
103
+ throw new Error(`unknown declaration: ${node.declaration}`);
104
+ }
105
+ }
106
+ else if (node.member) {
107
+ switch (node.member) {
108
+ // Prints out an alias within a declaration, which looks like:
109
+ // alias foo bar
110
+ // alias self.foo self.bar
111
+ case "alias": {
112
+ if (node.kind === "singleton") {
113
+ doc = ["alias self.", node.new_name, " self.", node.old_name];
114
+ }
115
+ else {
116
+ doc = ["alias ", node.new_name, " ", node.old_name];
117
+ }
118
+ break;
119
+ }
120
+ // Prints out an attr_* meta method, which looks like:
121
+ // attr_accessor foo
122
+ // attr_reader self.foo()
123
+ // attr_writer self.foo(@bar): String
124
+ case "attr_accessor":
125
+ case "attr_reader":
126
+ case "attr_writer": {
127
+ const parts = [node.member, " "];
128
+ if (node.kind === "singleton") {
129
+ parts.push("self.");
130
+ }
131
+ parts.push(node.name);
132
+ if (node.ivar_name === false) {
133
+ parts.push("()");
134
+ }
135
+ else if (node.ivar_name) {
136
+ parts.push("(", node.ivar_name, ")");
137
+ }
138
+ parts.push(": ", path.call(printType, "type"));
139
+ doc = group(parts);
140
+ break;
141
+ }
142
+ // Prints out a class or instance variable member, which looks like:
143
+ // @foo: String
144
+ // @@foo: String
145
+ case "class_variable":
146
+ case "instance_variable": {
147
+ doc = group([node.name, ": ", path.call(printType, "type")]);
148
+ break;
149
+ }
150
+ // Prints out a class instance variable member, which looks like:
151
+ // self.@foo: String
152
+ case "class_instance_variable": {
153
+ doc = ["self.", node.name, ": ", path.call(printType, "type")];
154
+ break;
155
+ }
156
+ // Prints out a mixin, which looks like:
157
+ // include Foo
158
+ // prepend Foo
159
+ // extend Foo
160
+ case "include":
161
+ case "extend":
162
+ case "prepend": {
163
+ const nodePath = path;
164
+ doc = group([node.member, " ", printNameAndArgs(nodePath)]);
165
+ break;
166
+ }
167
+ case "public":
168
+ case "private": {
169
+ doc = node.member;
170
+ break;
171
+ }
172
+ case "method_definition": {
173
+ const nodePath = path;
174
+ doc = printMethodDefinition(nodePath, node);
175
+ break;
176
+ }
177
+ /* istanbul ignore next */
178
+ default:
179
+ throw new Error(`unknown member: ${node.member}`);
180
+ }
181
+ }
182
+ else {
183
+ const ast = JSON.stringify(node, null, 2);
184
+ throw new Error(`Unsupported node encountered:\n${ast}`);
185
+ }
186
+ // An annotation can be attached to most kinds of nodes, and should be
187
+ // printed using %a{}. Certain nodes can't have annotations at all.
188
+ if (node.annotations && node.annotations.length > 0) {
189
+ const annotationsPath = path;
190
+ doc = [
191
+ join(hardline, annotationsPath.map((annotationPath) => {
192
+ const annotationNode = annotationPath.getValue();
193
+ // If there are already braces inside the annotation, then we're
194
+ // just going to print out the original string to avoid having to
195
+ // escape anything.
196
+ if (/[{}]/.test(annotationNode.string)) {
197
+ return getSource(annotationNode, opts);
198
+ }
199
+ return ["%a{", annotationNode.string, "}"];
200
+ }, "annotations")),
201
+ hardline,
202
+ doc
203
+ ];
204
+ }
205
+ // Comments come in as one whole string, so here we split it up into
206
+ // multiple lines and then prefix it with the pound sign.
207
+ if (node.comment) {
208
+ doc = [
209
+ join(hardline, node.comment.string
210
+ .slice(0, -1)
211
+ .split("\n")
212
+ .map((segment) => `# ${segment}`)),
213
+ hardline,
214
+ doc
215
+ ];
216
+ }
217
+ return doc;
218
+ // Prints out a string in the source, which looks like:
219
+ // 'foo'
220
+ function printString(node) {
221
+ // We're going to go straight to the source here, as if we don't then
222
+ // we're going to end up with the result of String#inspect, which does
223
+ // weird things to escape sequences.
224
+ const value = getSource(node, opts);
225
+ // Get the quote that was used in the source and the quote that we want to
226
+ // be using.
227
+ const originalQuote = value[0];
228
+ const preferredQuote = opts.rubySingleQuote ? "'" : '"';
229
+ // Determine if we're allowed to change the quote based on whether or not
230
+ // there is an escape sequence in the source string.
231
+ const quote = node.literal.includes("\\")
232
+ ? originalQuote
233
+ : preferredQuote;
234
+ return makeString(value.slice(1, -1), quote, false);
235
+ }
236
+ // Certain nodes are names with optional arguments attached, as in Array[A].
237
+ // We handle all of that printing centralized here.
238
+ function printNameAndArgs(path) {
239
+ const node = path.getValue();
240
+ if (node.args.length === 0) {
241
+ return node.name;
242
+ }
243
+ return group([
244
+ node.name,
245
+ "[",
246
+ join(", ", path.map(printType, "args")),
247
+ "]"
248
+ ]);
249
+ }
250
+ // This is the big function that prints out any individual type, which can
251
+ // look like all kinds of things, listed in the case statement below.
252
+ function printType(path, options) {
253
+ const node = path.getValue();
254
+ const forceParens = typeof options === "object" && options.forceParens;
255
+ switch (node.class) {
256
+ case "literal":
257
+ if (node.literal[0] === '"') {
258
+ return printString(node);
259
+ }
260
+ return node.literal;
261
+ case "optional": {
262
+ const nodePath = path;
263
+ return [
264
+ nodePath.call((typePath) => printType(typePath, { forceParens: true }), "type"),
265
+ "?"
266
+ ];
267
+ }
268
+ case "tuple": {
269
+ // If we don't have any sub types, we explicitly need the space in
270
+ // between the brackets to not confuse the parser.
271
+ if (node.types.length === 0) {
272
+ return "[ ]";
273
+ }
274
+ const nodePath = path;
275
+ return group([
276
+ "[",
277
+ join(", ", nodePath.map(printType, "types")),
278
+ "]"
279
+ ]);
280
+ }
281
+ case "union": {
282
+ const nodePath = path;
283
+ const doc = group(join([line, "| "], nodePath.map(printType, "types")));
284
+ if (forceParens) {
285
+ return ["(", doc, ")"];
286
+ }
287
+ return doc;
288
+ }
289
+ case "intersection": {
290
+ const nodePath = path;
291
+ const doc = group(join([line, "& "], nodePath.map((typePath) => printType(typePath, { forceParens: true }), "types")));
292
+ if (forceParens) {
293
+ return ["(", doc, ")"];
294
+ }
295
+ return doc;
296
+ }
297
+ case "class_singleton":
298
+ return ["singleton(", node.name, ")"];
299
+ case "proc":
300
+ return [
301
+ "^",
302
+ printMethodSignature(path)
303
+ ];
304
+ case "record": {
305
+ const nodePath = path;
306
+ const parts = [];
307
+ getSortedKeys(node.fields).forEach((field) => {
308
+ const fieldParts = [];
309
+ if (node.fields[field].joiner === "rocket") {
310
+ fieldParts.push(`${field} => `);
311
+ }
312
+ else {
313
+ fieldParts.push(`${field}: `);
314
+ }
315
+ fieldParts.push(nodePath.call(printType, "fields", field, "type"));
316
+ parts.push(fieldParts);
317
+ });
318
+ return group([
319
+ "{",
320
+ indent([line, join([",", line], parts)]),
321
+ line,
322
+ "}"
323
+ ]);
324
+ }
325
+ case "class_instance":
326
+ case "interface": {
327
+ const nodePath = path;
328
+ return printNameAndArgs(nodePath);
329
+ }
330
+ case "alias":
331
+ case "variable":
332
+ return node.name;
333
+ case "bool":
334
+ case "bot":
335
+ case "class":
336
+ case "instance":
337
+ case "nil":
338
+ case "self":
339
+ case "top":
340
+ case "untyped":
341
+ case "void":
342
+ return node.class;
343
+ /* istanbul ignore next */
344
+ default:
345
+ throw new Error(`unknown type: ${node.class}`);
346
+ }
347
+ }
348
+ // Prints out the members of a class, module, or interface.
349
+ function printMembers(path) {
350
+ let lastLine = null;
351
+ const docs = [];
352
+ path.each((memberPath) => {
353
+ const memberNode = memberPath.getValue();
354
+ if (lastLine !== null &&
355
+ memberNode.location.start.line - lastLine >= 2) {
356
+ docs.push([hardline, hardline]);
357
+ }
358
+ else {
359
+ docs.push(hardline);
360
+ }
361
+ docs.push(print(memberPath));
362
+ lastLine = memberNode.location.end.line;
363
+ }, "members");
364
+ return docs;
365
+ }
366
+ // Prints out the name of a class, interface, or module declaration.
367
+ // Additionally loops through each type parameter if there are any and print
368
+ // them out joined by commas. Checks for validation and variance.
369
+ function printNameAndTypeParams(path, node) {
370
+ if (node.type_params.params.length === 0) {
371
+ return node.name;
372
+ }
373
+ const docs = path.map((paramPath) => {
374
+ const node = paramPath.getValue();
375
+ const parts = [];
376
+ if (node.skip_validation) {
377
+ parts.push("unchecked");
378
+ }
379
+ if (node.variance === "covariant") {
380
+ parts.push("out");
381
+ }
382
+ else if (node.variance === "contravariant") {
383
+ parts.push("in");
384
+ }
385
+ return join(" ", [...parts, node.name]);
386
+ }, "type_params", "params");
387
+ return [node.name, "[", join(", ", docs), "]"];
388
+ }
389
+ // Returns an array of printed parameters so that the calling function can
390
+ // join them together in whatever way.
391
+ function printMethodParams(path) {
392
+ const node = path.getValue();
393
+ let parts = [];
394
+ // required positionals, as in (A)
395
+ parts = parts.concat(path.map(printMethodParam, "required_positionals"));
396
+ // optional positionals, as in (?A)
397
+ parts = parts.concat(path.map((paramPath) => ["?", printMethodParam(paramPath)], "optional_positionals"));
398
+ // rest positional, as in (*A)
399
+ if (node.rest_positionals) {
400
+ const restPositionalsPath = path;
401
+ parts.push([
402
+ "*",
403
+ restPositionalsPath.call(printMethodParam, "rest_positionals")
404
+ ]);
405
+ }
406
+ // trailing positionals are required positionals after a rest
407
+ parts = parts.concat(path.map(printMethodParam, "trailing_positionals"));
408
+ // required keywords, as in (a: A)
409
+ getSortedKeys(node.required_keywords).forEach((name) => {
410
+ parts.push([
411
+ name,
412
+ ": ",
413
+ path.call(printMethodParam, "required_keywords", name)
414
+ ]);
415
+ });
416
+ // optional keywords, as in (?a: A)
417
+ getSortedKeys(node.optional_keywords).forEach((name) => {
418
+ parts.push([
419
+ "?",
420
+ name,
421
+ ": ",
422
+ path.call(printMethodParam, "optional_keywords", name)
423
+ ]);
424
+ });
425
+ // rest keyword, as in (**A)
426
+ if (node.rest_keywords) {
427
+ const restKeywordsPath = path;
428
+ parts.push([
429
+ "**",
430
+ restKeywordsPath.call(printMethodParam, "rest_keywords")
431
+ ]);
432
+ }
433
+ return parts;
434
+ // Prints out a method parameter at a given path. Handles printing out the
435
+ // name if there is one (and whether or not it's escaped).
436
+ function printMethodParam(path) {
437
+ const node = path.getValue();
438
+ const parts = [path.call(printType, "type")];
439
+ if (node.name) {
440
+ parts.push(" ");
441
+ if (node.escaped) {
442
+ parts.push("`", node.name, "`");
443
+ }
444
+ else {
445
+ parts.push(node.name);
446
+ }
447
+ }
448
+ return parts;
449
+ }
450
+ }
451
+ // Prints out a specific method signature, which looks like:
452
+ // (T t) -> void
453
+ function printMethodSignature(path) {
454
+ const node = path.getValue();
455
+ const parts = [];
456
+ // We won't have a type_params key if we're printing a block
457
+ if (node.type_params && node.type_params.length > 0) {
458
+ parts.push("[", join(", ", node.type_params), "] ");
459
+ }
460
+ const params = path.call(printMethodParams, "type");
461
+ if (params.length > 0) {
462
+ parts.push("(", indent([softline, join([",", line], params)]), softline, ") ");
463
+ }
464
+ if (node.block) {
465
+ if (!node.block.required) {
466
+ parts.push("?");
467
+ }
468
+ parts.push("{", indent([line, path.call(printMethodSignature, "block")]), line, "} ");
469
+ }
470
+ parts.push("-> ", path.call((typePath) => printType(typePath, { forceParens: true }), "type", "return_type"));
471
+ return group(parts);
472
+ }
473
+ // Prints out a method definition, which looks like:
474
+ // def t: (T t) -> void
475
+ function printMethodDefinition(path, node) {
476
+ let typeDocs = path.map(printMethodSignature, "types");
477
+ if (node.overload) {
478
+ typeDocs.push("...");
479
+ }
480
+ if (typeDocs.length === 1) {
481
+ typeDocs = [" ", typeDocs[0]];
482
+ }
483
+ else {
484
+ typeDocs = indent(group([line, join([line, "| "], typeDocs)]));
485
+ }
486
+ const parts = ["def "];
487
+ if (node.kind === "singleton") {
488
+ parts.push("self.");
489
+ }
490
+ else if (node.kind === "singleton_instance") {
491
+ parts.push("self?.");
492
+ }
493
+ const escaped = isMethodNameEscaped();
494
+ parts.push(escaped ? `\`${node.name}\`` : node.name, ":", typeDocs);
495
+ return group(parts);
496
+ // Determine if a method name is escaped in the original source.
497
+ function isMethodNameEscaped() {
498
+ const pos = node.location.start_pos + 4;
499
+ const name = opts.originalText.slice(pos, pos + 2).trimStart();
500
+ return name[0] === "`" && name[1] !== ":";
501
+ }
502
+ }
503
+ },
504
+ // This is an escape-hatch to ignore nodes in the tree. If you have a comment
505
+ // that includes this pattern, then the entire node will be ignored and just
506
+ // the original source will be printed out.
507
+ hasPrettierIgnore(path) {
508
+ const node = path.getValue();
509
+ return ((node.comment && node.comment.string.includes("prettier-ignore")) || false);
510
+ },
511
+ // This function handles adding the format pragma to a source string. This is
512
+ // an optional workflow for incremental adoption.
513
+ insertPragma(text) {
514
+ return `# @format${text[0] === "#" ? "\n" : "\n\n"}${text}`;
515
+ }
516
+ };
517
+ exports.default = printer;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const prettier_1 = __importDefault(require("../prettier"));
7
+ const utils_1 = require("../utils");
8
+ const { group, indent, dedent, lineSuffix, mapDoc, markAsRoot, stripTrailingHardline } = prettier_1.default;
9
+ const parsers = {
10
+ css: "css",
11
+ javascript: "babel",
12
+ js: "babel",
13
+ less: "less",
14
+ markdown: "markdown",
15
+ ruby: "ruby",
16
+ scss: "scss"
17
+ };
18
+ // This function is in here because it handles embedded parser values. I don't
19
+ // have a test that exercises it because I'm not sure for which parser it is
20
+ // necessary, but since it's in prettier core I'm keeping it here.
21
+ /* istanbul ignore next */
22
+ function replaceNewlines(doc) {
23
+ return mapDoc(doc, (currentDoc) => typeof currentDoc === "string" && currentDoc.includes("\n")
24
+ ? currentDoc
25
+ .split(/(\n)/g)
26
+ .map((v, i) => (i % 2 === 0 ? v : utils_1.literallineWithoutBreakParent))
27
+ : currentDoc);
28
+ }
29
+ // Returns a number that represents the minimum amount of leading whitespace
30
+ // that is present on every line in the given string. So for example if you have
31
+ // the following heredoc:
32
+ //
33
+ // <<~HERE
34
+ // my
35
+ // content
36
+ // here
37
+ // HERE
38
+ //
39
+ // then the return value of this function would be 2. If you indented every line
40
+ // of the inner content 2 more spaces then this function would return 4.
41
+ function getCommonLeadingWhitespace(content) {
42
+ const pattern = /^\s+/;
43
+ return content
44
+ .split("\n")
45
+ .slice(0, -1)
46
+ .filter((line) => line.trim().length > 0)
47
+ .reduce((minimum, line) => {
48
+ const matched = pattern.exec(line);
49
+ const length = matched ? matched[0].length : 0;
50
+ return minimum === null ? length : Math.min(minimum, length);
51
+ }, content.length);
52
+ }
53
+ // Returns a new string with the common whitespace stripped out. Effectively it
54
+ // emulates what a squiggly heredoc does in Ruby.
55
+ function stripCommonLeadingWhitespace(content) {
56
+ const lines = content.split("\n");
57
+ const minimum = getCommonLeadingWhitespace(content);
58
+ return lines.map((line) => line.slice(minimum)).join("\n");
59
+ }
60
+ const embed = (path, print, textToDoc) => {
61
+ const node = path.getValue();
62
+ // Currently we only support embedded formatting on heredoc nodes
63
+ if (node.type !== "heredoc") {
64
+ return null;
65
+ }
66
+ // First, ensure that we don't have any interpolation
67
+ const { beging, body, ending } = node;
68
+ const isSquiggly = beging.body[2] === "~";
69
+ if (body.some((part) => part.type !== "@tstring_content")) {
70
+ return null;
71
+ }
72
+ // Next, find the parser associated with this heredoc (if there is one). For
73
+ // example, if you use <<~CSS, we'd hook it up to the css parser.
74
+ const parser = parsers[beging.body.slice(3).toLowerCase()];
75
+ if (!parser) {
76
+ return null;
77
+ }
78
+ // Get the content as if it were a source string.
79
+ let content = body.map((part) => part.body).join("");
80
+ // If we're using a squiggly heredoc, then we're going to manually strip off
81
+ // the leading whitespace of each line up to the minimum leading whitespace so
82
+ // that the embedded parser can handle that for us.
83
+ if (isSquiggly) {
84
+ content = stripCommonLeadingWhitespace(content);
85
+ }
86
+ // Pass that content into the embedded parser. Get back the doc node.
87
+ const formatted = [
88
+ utils_1.literallineWithoutBreakParent,
89
+ replaceNewlines(stripTrailingHardline(textToDoc(content, { parser })))
90
+ ];
91
+ // If we're using a squiggly heredoc, then we can properly handle indentation
92
+ // ourselves.
93
+ if (isSquiggly) {
94
+ return [
95
+ path.call(print, "beging"),
96
+ lineSuffix(dedent([
97
+ indent(markAsRoot(formatted)),
98
+ { type: "line", hard: true },
99
+ ending.trim()
100
+ ]))
101
+ ];
102
+ }
103
+ // Otherwise, we need to just assume it's formatted correctly and return the
104
+ // content as it is.
105
+ return markAsRoot([
106
+ path.call(print, "beging"),
107
+ lineSuffix(group([formatted, utils_1.literallineWithoutBreakParent, ending.trim()]))
108
+ ]);
109
+ };
110
+ exports.default = embed;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.printAlias = void 0;
7
+ const prettier_1 = __importDefault(require("../../prettier"));
8
+ const { addTrailingComment, align, group, hardline, line } = prettier_1.default;
9
+ // The `alias` keyword is used to make a method respond to another name as well
10
+ // as the current one. For example, to get the method `foo` to also respond to
11
+ // `bar`, you would:
12
+ //
13
+ // alias bar foo
14
+ //
15
+ // Now, in the current context you can call `bar` and it will execute the `foo`
16
+ // method.
17
+ //
18
+ // When you're aliasing two methods, you can either provide bare words (like the
19
+ // example above) or you can provide symbols (note that this includes dynamic
20
+ // symbols like :"foo-#{bar}-baz"). In general, to be consistent with the ruby
21
+ // style guide, we prefer bare words:
22
+ //
23
+ // https://github.com/rubocop-hq/ruby-style-guide#alias-method-lexically
24
+ //
25
+ // The `alias` node contains two children. The left and right align with the
26
+ // arguments passed to the keyword. So, for the above example the left would be
27
+ // the symbol literal `bar` and the right could be the symbol literal `foo`.
28
+ const printAlias = (path, opts, print) => {
29
+ const keyword = "alias ";
30
+ // In general, return the printed doc of the argument at the provided index.
31
+ // Special handling is given for symbol literals that are not bare words, as
32
+ // we convert those into bare words by just pulling out the ident node.
33
+ const printAliasArg = (argPath) => {
34
+ const argNode = argPath.getValue();
35
+ if (argNode.type === "symbol_literal") {
36
+ // If we're going to descend into the symbol literal to grab out the ident
37
+ // node, then we need to make sure we copy over any comments as well,
38
+ // otherwise we could accidentally skip printing them.
39
+ if (argNode.comments) {
40
+ argNode.comments.forEach((comment) => {
41
+ addTrailingComment(argNode.body[0], comment);
42
+ });
43
+ }
44
+ return argPath.call(print, "body", 0);
45
+ }
46
+ return print(argPath);
47
+ };
48
+ return group([
49
+ keyword,
50
+ path.call(printAliasArg, "body", 0),
51
+ group(align(keyword.length, [
52
+ // If the left child has any comments, then we need to explicitly break
53
+ // this into two lines
54
+ path.getValue().body[0].comments ? hardline : line,
55
+ path.call(printAliasArg, "body", 1)
56
+ ]))
57
+ ]);
58
+ };
59
+ exports.printAlias = printAlias;