1 //===- unittest/Format/FormatTestJS.cpp - Formatting unit tests for JS ----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "FormatTestUtils.h"
11 #include "clang/Format/Format.h"
12 #include "llvm/Support/Debug.h"
13 #include "gtest/gtest.h"
14
15 #define DEBUG_TYPE "format-test"
16
17 namespace clang {
18 namespace format {
19
20 class FormatTestJS : public ::testing::Test {
21 protected:
format(llvm::StringRef Code,unsigned Offset,unsigned Length,const FormatStyle & Style)22 static std::string format(llvm::StringRef Code, unsigned Offset,
23 unsigned Length, const FormatStyle &Style) {
24 DEBUG(llvm::errs() << "---\n");
25 DEBUG(llvm::errs() << Code << "\n\n");
26 std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
27 bool IncompleteFormat = false;
28 tooling::Replacements Replaces =
29 reformat(Style, Code, Ranges, "<stdin>", &IncompleteFormat);
30 EXPECT_FALSE(IncompleteFormat);
31 auto Result = applyAllReplacements(Code, Replaces);
32 EXPECT_TRUE(static_cast<bool>(Result));
33 DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
34 return *Result;
35 }
36
format(llvm::StringRef Code,const FormatStyle & Style=getGoogleStyle (FormatStyle::LK_JavaScript))37 static std::string format(
38 llvm::StringRef Code,
39 const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
40 return format(Code, 0, Code.size(), Style);
41 }
42
getGoogleJSStyleWithColumns(unsigned ColumnLimit)43 static FormatStyle getGoogleJSStyleWithColumns(unsigned ColumnLimit) {
44 FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
45 Style.ColumnLimit = ColumnLimit;
46 return Style;
47 }
48
verifyFormat(llvm::StringRef Code,const FormatStyle & Style=getGoogleStyle (FormatStyle::LK_JavaScript))49 static void verifyFormat(
50 llvm::StringRef Code,
51 const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
52 std::string Result = format(test::messUp(Code), Style);
53 EXPECT_EQ(Code.str(), Result) << "Formatted:\n" << Result;
54 }
55
verifyFormat(llvm::StringRef Expected,llvm::StringRef Code,const FormatStyle & Style=getGoogleStyle (FormatStyle::LK_JavaScript))56 static void verifyFormat(
57 llvm::StringRef Expected,
58 llvm::StringRef Code,
59 const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
60 std::string Result = format(Code, Style);
61 EXPECT_EQ(Expected.str(), Result) << "Formatted:\n" << Result;
62 }
63 };
64
TEST_F(FormatTestJS,BlockComments)65 TEST_F(FormatTestJS, BlockComments) {
66 verifyFormat("/* aaaaaaaaaaaaa */ aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
67 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
68 }
69
TEST_F(FormatTestJS,UnderstandsJavaScriptOperators)70 TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
71 verifyFormat("a == = b;");
72 verifyFormat("a != = b;");
73
74 verifyFormat("a === b;");
75 verifyFormat("aaaaaaa ===\n b;", getGoogleJSStyleWithColumns(10));
76 verifyFormat("a !== b;");
77 verifyFormat("aaaaaaa !==\n b;", getGoogleJSStyleWithColumns(10));
78 verifyFormat("if (a + b + c +\n"
79 " d !==\n"
80 " e + f + g)\n"
81 " q();",
82 getGoogleJSStyleWithColumns(20));
83
84 verifyFormat("a >> >= b;");
85
86 verifyFormat("a >>> b;");
87 verifyFormat("aaaaaaa >>>\n b;", getGoogleJSStyleWithColumns(10));
88 verifyFormat("a >>>= b;");
89 verifyFormat("aaaaaaa >>>=\n b;", getGoogleJSStyleWithColumns(10));
90 verifyFormat("if (a + b + c +\n"
91 " d >>>\n"
92 " e + f + g)\n"
93 " q();",
94 getGoogleJSStyleWithColumns(20));
95 verifyFormat("var x = aaaaaaaaaa ?\n"
96 " bbbbbb :\n"
97 " ccc;",
98 getGoogleJSStyleWithColumns(20));
99
100 verifyFormat("var b = a.map((x) => x + 1);");
101 verifyFormat("return ('aaa') in bbbb;");
102 verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
103 " aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
104 FormatStyle Style = getGoogleJSStyleWithColumns(80);
105 Style.AlignOperands = true;
106 verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
107 " aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
108 Style);
109 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
110 verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa()\n"
111 " in aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
112 Style);
113
114 // ES6 spread operator.
115 verifyFormat("someFunction(...a);");
116 verifyFormat("var x = [1, ...a, 2];");
117 }
118
TEST_F(FormatTestJS,UnderstandsAmpAmp)119 TEST_F(FormatTestJS, UnderstandsAmpAmp) {
120 verifyFormat("e && e.SomeFunction();");
121 }
122
TEST_F(FormatTestJS,LiteralOperatorsCanBeKeywords)123 TEST_F(FormatTestJS, LiteralOperatorsCanBeKeywords) {
124 verifyFormat("not.and.or.not_eq = 1;");
125 }
126
TEST_F(FormatTestJS,ReservedWords)127 TEST_F(FormatTestJS, ReservedWords) {
128 // JavaScript reserved words (aka keywords) are only illegal when used as
129 // Identifiers, but are legal as IdentifierNames.
130 verifyFormat("x.class.struct = 1;");
131 verifyFormat("x.case = 1;");
132 verifyFormat("x.interface = 1;");
133 verifyFormat("x.for = 1;");
134 verifyFormat("x.of() = 1;");
135 verifyFormat("x.in() = 1;");
136 verifyFormat("x.let() = 1;");
137 verifyFormat("x.var() = 1;");
138 verifyFormat("x = {\n"
139 " a: 12,\n"
140 " interface: 1,\n"
141 " switch: 1,\n"
142 "};");
143 verifyFormat("var struct = 2;");
144 verifyFormat("var union = 2;");
145 verifyFormat("var interface = 2;");
146 verifyFormat("interface = 2;");
147 verifyFormat("x = interface instanceof y;");
148 }
149
TEST_F(FormatTestJS,CppKeywords)150 TEST_F(FormatTestJS, CppKeywords) {
151 // Make sure we don't mess stuff up because of C++ keywords.
152 verifyFormat("return operator && (aa);");
153 }
154
TEST_F(FormatTestJS,ES6DestructuringAssignment)155 TEST_F(FormatTestJS, ES6DestructuringAssignment) {
156 verifyFormat("var [a, b, c] = [1, 2, 3];");
157 verifyFormat("const [a, b, c] = [1, 2, 3];");
158 verifyFormat("let [a, b, c] = [1, 2, 3];");
159 verifyFormat("var {a, b} = {a: 1, b: 2};");
160 verifyFormat("let {a, b} = {a: 1, b: 2};");
161 }
162
TEST_F(FormatTestJS,ContainerLiterals)163 TEST_F(FormatTestJS, ContainerLiterals) {
164 verifyFormat("var x = {y: function(a) { return a; }};");
165 verifyFormat("return {\n"
166 " link: function() {\n"
167 " f(); //\n"
168 " }\n"
169 "};");
170 verifyFormat("return {\n"
171 " a: a,\n"
172 " link: function() {\n"
173 " f(); //\n"
174 " }\n"
175 "};");
176 verifyFormat("return {\n"
177 " a: a,\n"
178 " link: function() {\n"
179 " f(); //\n"
180 " },\n"
181 " link: function() {\n"
182 " f(); //\n"
183 " }\n"
184 "};");
185 verifyFormat("var stuff = {\n"
186 " // comment for update\n"
187 " update: false,\n"
188 " // comment for modules\n"
189 " modules: false,\n"
190 " // comment for tasks\n"
191 " tasks: false\n"
192 "};");
193 verifyFormat("return {\n"
194 " 'finish':\n"
195 " //\n"
196 " a\n"
197 "};");
198 verifyFormat("var obj = {\n"
199 " fooooooooo: function(x) {\n"
200 " return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
201 " }\n"
202 "};");
203 // Simple object literal, as opposed to enum style below.
204 verifyFormat("var obj = {a: 123};");
205 // Enum style top level assignment.
206 verifyFormat("X = {\n a: 123\n};");
207 verifyFormat("X.Y = {\n a: 123\n};");
208 // But only on the top level, otherwise its a plain object literal assignment.
209 verifyFormat("function x() {\n"
210 " y = {z: 1};\n"
211 "}");
212 verifyFormat("x = foo && {a: 123};");
213
214 // Arrow functions in object literals.
215 verifyFormat("var x = {y: (a) => { return a; }};");
216 verifyFormat("var x = {y: (a) => a};");
217
218 // Computed keys.
219 verifyFormat("var x = {[a]: 1, b: 2, [c]: 3};");
220 verifyFormat("var x = {\n"
221 " [a]: 1,\n"
222 " b: 2,\n"
223 " [c]: 3,\n"
224 "};");
225
226 // Object literals can leave out labels.
227 verifyFormat("f({a}, () => {\n"
228 " g(); //\n"
229 "});");
230
231 // Keys can be quoted.
232 verifyFormat("var x = {\n"
233 " a: a,\n"
234 " b: b,\n"
235 " 'c': c,\n"
236 "};");
237 }
238
TEST_F(FormatTestJS,MethodsInObjectLiterals)239 TEST_F(FormatTestJS, MethodsInObjectLiterals) {
240 verifyFormat("var o = {\n"
241 " value: 'test',\n"
242 " get value() { // getter\n"
243 " return this.value;\n"
244 " }\n"
245 "};");
246 verifyFormat("var o = {\n"
247 " value: 'test',\n"
248 " set value(val) { // setter\n"
249 " this.value = val;\n"
250 " }\n"
251 "};");
252 verifyFormat("var o = {\n"
253 " value: 'test',\n"
254 " someMethod(val) { // method\n"
255 " doSomething(this.value + val);\n"
256 " }\n"
257 "};");
258 verifyFormat("var o = {\n"
259 " someMethod(val) { // method\n"
260 " doSomething(this.value + val);\n"
261 " },\n"
262 " someOtherMethod(val) { // method\n"
263 " doSomething(this.value + val);\n"
264 " }\n"
265 "};");
266 }
267
TEST_F(FormatTestJS,SpacesInContainerLiterals)268 TEST_F(FormatTestJS, SpacesInContainerLiterals) {
269 verifyFormat("var arr = [1, 2, 3];");
270 verifyFormat("f({a: 1, b: 2, c: 3});");
271
272 verifyFormat("var object_literal_with_long_name = {\n"
273 " a: 'aaaaaaaaaaaaaaaaaa',\n"
274 " b: 'bbbbbbbbbbbbbbbbbb'\n"
275 "};");
276
277 verifyFormat("f({a: 1, b: 2, c: 3});",
278 getChromiumStyle(FormatStyle::LK_JavaScript));
279 verifyFormat("f({'a': [{}]});");
280 }
281
TEST_F(FormatTestJS,SingleQuotedStrings)282 TEST_F(FormatTestJS, SingleQuotedStrings) {
283 verifyFormat("this.function('', true);");
284 }
285
TEST_F(FormatTestJS,GoogScopes)286 TEST_F(FormatTestJS, GoogScopes) {
287 verifyFormat("goog.scope(function() {\n"
288 "var x = a.b;\n"
289 "var y = c.d;\n"
290 "}); // goog.scope");
291 verifyFormat("goog.scope(function() {\n"
292 "// test\n"
293 "var x = 0;\n"
294 "// test\n"
295 "});");
296 }
297
TEST_F(FormatTestJS,GoogModules)298 TEST_F(FormatTestJS, GoogModules) {
299 verifyFormat("goog.module('this.is.really.absurdly.long');",
300 getGoogleJSStyleWithColumns(40));
301 verifyFormat("goog.require('this.is.really.absurdly.long');",
302 getGoogleJSStyleWithColumns(40));
303 verifyFormat("goog.provide('this.is.really.absurdly.long');",
304 getGoogleJSStyleWithColumns(40));
305 verifyFormat("var long = goog.require('this.is.really.absurdly.long');",
306 getGoogleJSStyleWithColumns(40));
307 verifyFormat("goog.setTestOnly('this.is.really.absurdly.long');",
308 getGoogleJSStyleWithColumns(40));
309 verifyFormat("goog.forwardDeclare('this.is.really.absurdly.long');",
310 getGoogleJSStyleWithColumns(40));
311
312 // These should be wrapped normally.
313 verifyFormat(
314 "var MyLongClassName =\n"
315 " goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
316 }
317
TEST_F(FormatTestJS,FormatsNamespaces)318 TEST_F(FormatTestJS, FormatsNamespaces) {
319 verifyFormat("namespace Foo {\n"
320 " export let x = 1;\n"
321 "}\n");
322 verifyFormat("declare namespace Foo {\n"
323 " export let x: number;\n"
324 "}\n");
325 }
326
TEST_F(FormatTestJS,FormatsFreestandingFunctions)327 TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
328 verifyFormat("function outer1(a, b) {\n"
329 " function inner1(a, b) { return a; }\n"
330 " inner1(a, b);\n"
331 "}\n"
332 "function outer2(a, b) {\n"
333 " function inner2(a, b) { return a; }\n"
334 " inner2(a, b);\n"
335 "}");
336 verifyFormat("function f() {}");
337 }
338
TEST_F(FormatTestJS,GeneratorFunctions)339 TEST_F(FormatTestJS, GeneratorFunctions) {
340 verifyFormat("function* f() {\n"
341 " let x = 1;\n"
342 " yield x;\n"
343 " yield* something();\n"
344 "}");
345 verifyFormat("function*\n"
346 " f() {\n"
347 "}",
348 getGoogleJSStyleWithColumns(8));
349 verifyFormat("export function* f() {\n"
350 " yield 1;\n"
351 "}\n");
352 verifyFormat("class X {\n"
353 " * generatorMethod() { yield x; }\n"
354 "}");
355 }
356
TEST_F(FormatTestJS,AsyncFunctions)357 TEST_F(FormatTestJS, AsyncFunctions) {
358 verifyFormat("async function f() {\n"
359 " let x = 1;\n"
360 " return fetch(x);\n"
361 "}");
362 verifyFormat("async function* f() {\n"
363 " yield fetch(x);\n"
364 "}");
365 verifyFormat("export async function f() {\n"
366 " return fetch(x);\n"
367 "}");
368 verifyFormat("class X {\n"
369 " async asyncMethod() { return fetch(1); }\n"
370 "}");
371 verifyFormat("function initialize() {\n"
372 " // Comment.\n"
373 " return async.then();\n"
374 "}\n");
375 }
376
TEST_F(FormatTestJS,ArrayLiterals)377 TEST_F(FormatTestJS, ArrayLiterals) {
378 verifyFormat("var aaaaa: List<SomeThing> =\n"
379 " [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];");
380 verifyFormat("return [\n"
381 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
382 " ccccccccccccccccccccccccccc\n"
383 "];");
384 verifyFormat("return [\n"
385 " aaaa().bbbbbbbb('A'),\n"
386 " aaaa().bbbbbbbb('B'),\n"
387 " aaaa().bbbbbbbb('C'),\n"
388 "];");
389 verifyFormat("var someVariable = SomeFunction([\n"
390 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
391 " ccccccccccccccccccccccccccc\n"
392 "]);");
393 verifyFormat("var someVariable = SomeFunction([\n"
394 " [aaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbb],\n"
395 "]);",
396 getGoogleJSStyleWithColumns(51));
397 verifyFormat("var someVariable = SomeFunction(aaaa, [\n"
398 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
399 " ccccccccccccccccccccccccccc\n"
400 "]);");
401 verifyFormat("var someVariable = SomeFunction(\n"
402 " aaaa,\n"
403 " [\n"
404 " aaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
405 " cccccccccccccccccccccccccc\n"
406 " ],\n"
407 " aaaa);");
408 verifyFormat("var aaaa = aaaaa || // wrap\n"
409 " [];");
410
411 verifyFormat("someFunction([], {a: a});");
412 }
413
TEST_F(FormatTestJS,ColumnLayoutForArrayLiterals)414 TEST_F(FormatTestJS, ColumnLayoutForArrayLiterals) {
415 verifyFormat("var array = [\n"
416 " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
417 " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
418 "];");
419 verifyFormat("var array = someFunction([\n"
420 " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
421 " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
422 "]);");
423 }
424
TEST_F(FormatTestJS,FunctionLiterals)425 TEST_F(FormatTestJS, FunctionLiterals) {
426 verifyFormat("doFoo(function() {});");
427 verifyFormat("doFoo(function() { return 1; });");
428 verifyFormat("var func = function() {\n"
429 " return 1;\n"
430 "};");
431 verifyFormat("var func = //\n"
432 " function() {\n"
433 " return 1;\n"
434 "};");
435 verifyFormat("return {\n"
436 " body: {\n"
437 " setAttribute: function(key, val) { this[key] = val; },\n"
438 " getAttribute: function(key) { return this[key]; },\n"
439 " style: {direction: ''}\n"
440 " }\n"
441 "};");
442 verifyFormat("abc = xyz ? function() {\n"
443 " return 1;\n"
444 "} : function() {\n"
445 " return -1;\n"
446 "};");
447
448 verifyFormat("var closure = goog.bind(\n"
449 " function() { // comment\n"
450 " foo();\n"
451 " bar();\n"
452 " },\n"
453 " this, arg1IsReallyLongAndNeeedsLineBreaks,\n"
454 " arg3IsReallyLongAndNeeedsLineBreaks);");
455 verifyFormat("var closure = goog.bind(function() { // comment\n"
456 " foo();\n"
457 " bar();\n"
458 "}, this);");
459 verifyFormat("return {\n"
460 " a: 'E',\n"
461 " b: function() {\n"
462 " return function() {\n"
463 " f(); //\n"
464 " };\n"
465 " }\n"
466 "};");
467 verifyFormat("{\n"
468 " var someVariable = function(x) {\n"
469 " return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
470 " };\n"
471 "}");
472 verifyFormat("someLooooooooongFunction(\n"
473 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
474 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
475 " function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
476 " // code\n"
477 " });");
478
479 verifyFormat("f({a: function() { return 1; }});",
480 getGoogleJSStyleWithColumns(33));
481 verifyFormat("f({\n"
482 " a: function() { return 1; }\n"
483 "});",
484 getGoogleJSStyleWithColumns(32));
485
486 verifyFormat("return {\n"
487 " a: function SomeFunction() {\n"
488 " // ...\n"
489 " return 1;\n"
490 " }\n"
491 "};");
492 verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
493 " .then(goog.bind(function(aaaaaaaaaaa) {\n"
494 " someFunction();\n"
495 " someFunction();\n"
496 " }, this), aaaaaaaaaaaaaaaaa);");
497
498 verifyFormat("someFunction(goog.bind(function() {\n"
499 " doSomething();\n"
500 " doSomething();\n"
501 "}, this), goog.bind(function() {\n"
502 " doSomething();\n"
503 " doSomething();\n"
504 "}, this));");
505
506 // FIXME: This is bad, we should be wrapping before "function() {".
507 verifyFormat("someFunction(function() {\n"
508 " doSomething(); // break\n"
509 "})\n"
510 " .doSomethingElse(\n"
511 " // break\n"
512 " );");
513 }
514
TEST_F(FormatTestJS,InliningFunctionLiterals)515 TEST_F(FormatTestJS, InliningFunctionLiterals) {
516 FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
517 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
518 verifyFormat("var func = function() {\n"
519 " return 1;\n"
520 "};",
521 Style);
522 verifyFormat("var func = doSomething(function() { return 1; });", Style);
523 verifyFormat("var outer = function() {\n"
524 " var inner = function() { return 1; }\n"
525 "};",
526 Style);
527 verifyFormat("function outer1(a, b) {\n"
528 " function inner1(a, b) { return a; }\n"
529 "}",
530 Style);
531
532 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
533 verifyFormat("var func = function() { return 1; };", Style);
534 verifyFormat("var func = doSomething(function() { return 1; });", Style);
535 verifyFormat(
536 "var outer = function() { var inner = function() { return 1; } };",
537 Style);
538 verifyFormat("function outer1(a, b) {\n"
539 " function inner1(a, b) { return a; }\n"
540 "}",
541 Style);
542
543 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
544 verifyFormat("var func = function() {\n"
545 " return 1;\n"
546 "};",
547 Style);
548 verifyFormat("var func = doSomething(function() {\n"
549 " return 1;\n"
550 "});",
551 Style);
552 verifyFormat("var outer = function() {\n"
553 " var inner = function() {\n"
554 " return 1;\n"
555 " }\n"
556 "};",
557 Style);
558 verifyFormat("function outer1(a, b) {\n"
559 " function inner1(a, b) {\n"
560 " return a;\n"
561 " }\n"
562 "}",
563 Style);
564
565 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
566 verifyFormat("var func = function() {\n"
567 " return 1;\n"
568 "};",
569 Style);
570 }
571
TEST_F(FormatTestJS,MultipleFunctionLiterals)572 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
573 verifyFormat("promise.then(\n"
574 " function success() {\n"
575 " doFoo();\n"
576 " doBar();\n"
577 " },\n"
578 " function error() {\n"
579 " doFoo();\n"
580 " doBaz();\n"
581 " },\n"
582 " []);\n");
583 verifyFormat("promise.then(\n"
584 " function success() {\n"
585 " doFoo();\n"
586 " doBar();\n"
587 " },\n"
588 " [],\n"
589 " function error() {\n"
590 " doFoo();\n"
591 " doBaz();\n"
592 " });\n");
593 verifyFormat("promise.then(\n"
594 " [],\n"
595 " function success() {\n"
596 " doFoo();\n"
597 " doBar();\n"
598 " },\n"
599 " function error() {\n"
600 " doFoo();\n"
601 " doBaz();\n"
602 " });\n");
603
604 verifyFormat("getSomeLongPromise()\n"
605 " .then(function(value) { body(); })\n"
606 " .thenCatch(function(error) {\n"
607 " body();\n"
608 " body();\n"
609 " });");
610 verifyFormat("getSomeLongPromise()\n"
611 " .then(function(value) {\n"
612 " body();\n"
613 " body();\n"
614 " })\n"
615 " .thenCatch(function(error) {\n"
616 " body();\n"
617 " body();\n"
618 " });");
619
620 verifyFormat("getSomeLongPromise()\n"
621 " .then(function(value) { body(); })\n"
622 " .thenCatch(function(error) { body(); });");
623
624 verifyFormat("return [aaaaaaaaaaaaaaaaaaaaaa]\n"
625 " .aaaaaaa(function() {\n"
626 " //\n"
627 " })\n"
628 " .bbbbbb();");
629 }
630
TEST_F(FormatTestJS,ArrowFunctions)631 TEST_F(FormatTestJS, ArrowFunctions) {
632 verifyFormat("var x = (a) => {\n"
633 " return a;\n"
634 "};");
635 verifyFormat("var x = (a) => {\n"
636 " function y() { return 42; }\n"
637 " return a;\n"
638 "};");
639 verifyFormat("var x = (a: type): {some: type} => {\n"
640 " return a;\n"
641 "};");
642 verifyFormat("var x = (a) => a;");
643 verifyFormat("return () => [];");
644 verifyFormat("var aaaaaaaaaaaaaaaaaaaa = {\n"
645 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
646 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
647 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) =>\n"
648 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
649 "};");
650 verifyFormat("var a = a.aaaaaaa(\n"
651 " (a: a) => aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) &&\n"
652 " aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
653 verifyFormat("var a = a.aaaaaaa(\n"
654 " (a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) ?\n"
655 " aaaaaaaaaaaaaaaaaaaaa(bbbbbbb) :\n"
656 " aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
657
658 // FIXME: This is bad, we should be wrapping before "() => {".
659 verifyFormat("someFunction(() => {\n"
660 " doSomething(); // break\n"
661 "})\n"
662 " .doSomethingElse(\n"
663 " // break\n"
664 " );");
665 }
666
TEST_F(FormatTestJS,ReturnStatements)667 TEST_F(FormatTestJS, ReturnStatements) {
668 verifyFormat("function() {\n"
669 " return [hello, world];\n"
670 "}");
671 }
672
TEST_F(FormatTestJS,ForLoops)673 TEST_F(FormatTestJS, ForLoops) {
674 verifyFormat("for (var i in [2, 3]) {\n"
675 "}");
676 verifyFormat("for (var i of [2, 3]) {\n"
677 "}");
678 verifyFormat("for (let {a, b} of x) {\n"
679 "}");
680 verifyFormat("for (let {a, b} in x) {\n"
681 "}");
682 }
683
TEST_F(FormatTestJS,WrapRespectsAutomaticSemicolonInsertion)684 TEST_F(FormatTestJS, WrapRespectsAutomaticSemicolonInsertion) {
685 // The following statements must not wrap, as otherwise the program meaning
686 // would change due to automatic semicolon insertion.
687 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
688 verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10));
689 verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10));
690 verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10));
691 verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
692 verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
693 verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
694 verifyFormat("return [\n"
695 " aaa\n"
696 "];",
697 getGoogleJSStyleWithColumns(12));
698 }
699
TEST_F(FormatTestJS,AutomaticSemicolonInsertionHeuristic)700 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
701 verifyFormat("a\n"
702 "b;",
703 " a \n"
704 " b ;");
705 verifyFormat("a()\n"
706 "b;",
707 " a ()\n"
708 " b ;");
709 verifyFormat("a[b]\n"
710 "c;",
711 "a [b]\n"
712 "c ;");
713 verifyFormat("1\n"
714 "a;",
715 "1 \n"
716 "a ;");
717 verifyFormat("a\n"
718 "1;",
719 "a \n"
720 "1 ;");
721 verifyFormat("a\n"
722 "'x';",
723 "a \n"
724 " 'x';");
725 verifyFormat("a++\n"
726 "b;",
727 "a ++\n"
728 "b ;");
729 verifyFormat("a\n"
730 "!b && c;",
731 "a \n"
732 " ! b && c;");
733 verifyFormat("a\n"
734 "if (1) f();",
735 " a\n"
736 " if (1) f();");
737 verifyFormat("a\n"
738 "class X {}",
739 " a\n"
740 " class X {}");
741 verifyFormat("var a", "var\n"
742 "a");
743 verifyFormat("x instanceof String", "x\n"
744 "instanceof\n"
745 "String");
746 verifyFormat("function f(@Foo bar) {}", "function f(@Foo\n"
747 " bar) {}");
748 }
749
TEST_F(FormatTestJS,ClosureStyleCasts)750 TEST_F(FormatTestJS, ClosureStyleCasts) {
751 verifyFormat("var x = /** @type {foo} */ (bar);");
752 }
753
TEST_F(FormatTestJS,TryCatch)754 TEST_F(FormatTestJS, TryCatch) {
755 verifyFormat("try {\n"
756 " f();\n"
757 "} catch (e) {\n"
758 " g();\n"
759 "} finally {\n"
760 " h();\n"
761 "}");
762
763 // But, of course, "catch" is a perfectly fine function name in JavaScript.
764 verifyFormat("someObject.catch();");
765 verifyFormat("someObject.new();");
766 verifyFormat("someObject.delete();");
767 }
768
TEST_F(FormatTestJS,StringLiteralConcatenation)769 TEST_F(FormatTestJS, StringLiteralConcatenation) {
770 verifyFormat("var literal = 'hello ' +\n"
771 " 'world';");
772 }
773
TEST_F(FormatTestJS,RegexLiteralClassification)774 TEST_F(FormatTestJS, RegexLiteralClassification) {
775 // Regex literals.
776 verifyFormat("var regex = /abc/;");
777 verifyFormat("f(/abc/);");
778 verifyFormat("f(abc, /abc/);");
779 verifyFormat("some_map[/abc/];");
780 verifyFormat("var x = a ? /abc/ : /abc/;");
781 verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
782 verifyFormat("var x = !/abc/.test(y);");
783 verifyFormat("var x = a && /abc/.test(y);");
784 verifyFormat("var x = a || /abc/.test(y);");
785 verifyFormat("var x = a + /abc/.search(y);");
786 verifyFormat("/abc/.search(y);");
787 verifyFormat("var regexs = {/abc/, /abc/};");
788 verifyFormat("return /abc/;");
789
790 // Not regex literals.
791 verifyFormat("var a = a / 2 + b / 3;");
792 verifyFormat("var a = a++ / 2;");
793 // Prefix unary can operate on regex literals, not that it makes sense.
794 verifyFormat("var a = ++/a/;");
795
796 // This is a known issue, regular expressions are incorrectly detected if
797 // directly following a closing parenthesis.
798 verifyFormat("if (foo) / bar /.exec(baz);");
799 }
800
TEST_F(FormatTestJS,RegexLiteralSpecialCharacters)801 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
802 verifyFormat("var regex = /=/;");
803 verifyFormat("var regex = /a*/;");
804 verifyFormat("var regex = /a+/;");
805 verifyFormat("var regex = /a?/;");
806 verifyFormat("var regex = /.a./;");
807 verifyFormat("var regex = /a\\*/;");
808 verifyFormat("var regex = /^a$/;");
809 verifyFormat("var regex = /\\/a/;");
810 verifyFormat("var regex = /(?:x)/;");
811 verifyFormat("var regex = /x(?=y)/;");
812 verifyFormat("var regex = /x(?!y)/;");
813 verifyFormat("var regex = /x|y/;");
814 verifyFormat("var regex = /a{2}/;");
815 verifyFormat("var regex = /a{1,3}/;");
816
817 verifyFormat("var regex = /[abc]/;");
818 verifyFormat("var regex = /[^abc]/;");
819 verifyFormat("var regex = /[\\b]/;");
820 verifyFormat("var regex = /[/]/;");
821 verifyFormat("var regex = /[\\/]/;");
822 verifyFormat("var regex = /\\[/;");
823 verifyFormat("var regex = /\\\\[/]/;");
824 verifyFormat("var regex = /}[\"]/;");
825 verifyFormat("var regex = /}[/\"]/;");
826 verifyFormat("var regex = /}[\"/]/;");
827
828 verifyFormat("var regex = /\\b/;");
829 verifyFormat("var regex = /\\B/;");
830 verifyFormat("var regex = /\\d/;");
831 verifyFormat("var regex = /\\D/;");
832 verifyFormat("var regex = /\\f/;");
833 verifyFormat("var regex = /\\n/;");
834 verifyFormat("var regex = /\\r/;");
835 verifyFormat("var regex = /\\s/;");
836 verifyFormat("var regex = /\\S/;");
837 verifyFormat("var regex = /\\t/;");
838 verifyFormat("var regex = /\\v/;");
839 verifyFormat("var regex = /\\w/;");
840 verifyFormat("var regex = /\\W/;");
841 verifyFormat("var regex = /a(a)\\1/;");
842 verifyFormat("var regex = /\\0/;");
843 verifyFormat("var regex = /\\\\/g;");
844 verifyFormat("var regex = /\\a\\\\/g;");
845 verifyFormat("var regex = /\a\\//g;");
846 verifyFormat("var regex = /a\\//;\n"
847 "var x = 0;");
848 verifyFormat("var regex = /'/g;", "var regex = /'/g ;");
849 verifyFormat("var regex = /'/g; //'", "var regex = /'/g ; //'");
850 verifyFormat("var regex = /\\/*/;\n"
851 "var x = 0;",
852 "var regex = /\\/*/;\n"
853 "var x=0;");
854 verifyFormat("var x = /a\\//;", "var x = /a\\// \n;");
855 verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
856 verifyFormat("var regex =\n"
857 " /\"/;",
858 getGoogleJSStyleWithColumns(15));
859 verifyFormat("var regex = //\n"
860 " /a/;");
861 verifyFormat("var regexs = [\n"
862 " /d/, //\n"
863 " /aa/, //\n"
864 "];");
865 }
866
TEST_F(FormatTestJS,RegexLiteralModifiers)867 TEST_F(FormatTestJS, RegexLiteralModifiers) {
868 verifyFormat("var regex = /abc/g;");
869 verifyFormat("var regex = /abc/i;");
870 verifyFormat("var regex = /abc/m;");
871 verifyFormat("var regex = /abc/y;");
872 }
873
TEST_F(FormatTestJS,RegexLiteralLength)874 TEST_F(FormatTestJS, RegexLiteralLength) {
875 verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
876 getGoogleJSStyleWithColumns(60));
877 verifyFormat("var regex =\n"
878 " /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
879 getGoogleJSStyleWithColumns(60));
880 verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
881 getGoogleJSStyleWithColumns(50));
882 }
883
TEST_F(FormatTestJS,RegexLiteralExamples)884 TEST_F(FormatTestJS, RegexLiteralExamples) {
885 verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
886 }
887
TEST_F(FormatTestJS,TypeAnnotations)888 TEST_F(FormatTestJS, TypeAnnotations) {
889 verifyFormat("var x: string;");
890 verifyFormat("var x: {a: string; b: number;} = {};");
891 verifyFormat("function x(): string {\n return 'x';\n}");
892 verifyFormat("function x(): {x: string} {\n return {x: 'x'};\n}");
893 verifyFormat("function x(y: string): string {\n return 'x';\n}");
894 verifyFormat("for (var y: string in x) {\n x();\n}");
895 verifyFormat("for (var y: string of x) {\n x();\n}");
896 verifyFormat("function x(y: {a?: number;} = {}): number {\n"
897 " return 12;\n"
898 "}");
899 verifyFormat("((a: string, b: number): string => a + b);");
900 verifyFormat("var x: (y: number) => string;");
901 verifyFormat("var x: P<string, (a: number) => string>;");
902 verifyFormat("var x = {y: function(): z { return 1; }};");
903 verifyFormat("var x = {y: function(): {a: number} { return 1; }};");
904 verifyFormat("function someFunc(args: string[]):\n"
905 " {longReturnValue: string[]} {}",
906 getGoogleJSStyleWithColumns(60));
907 }
908
TEST_F(FormatTestJS,UnionIntersectionTypes)909 TEST_F(FormatTestJS, UnionIntersectionTypes) {
910 verifyFormat("let x: A|B = A | B;");
911 verifyFormat("let x: A&B|C = A & B;");
912 verifyFormat("let x: Foo<A|B> = new Foo<A|B>();");
913 verifyFormat("function(x: A|B): C&D {}");
914 verifyFormat("function(x: A|B = A | B): C&D {}");
915 verifyFormat("function x(path: number|string) {}");
916 verifyFormat("function x(): string|number {}");
917 verifyFormat("type Foo = Bar|Baz;");
918 verifyFormat("type Foo = Bar<X>|Baz;");
919 verifyFormat("type Foo = (Bar<X>|Baz);");
920 verifyFormat("let x: Bar|Baz;");
921 verifyFormat("let x: Bar<X>|Baz;");
922 verifyFormat("let x: (Foo|Bar)[];");
923 }
924
TEST_F(FormatTestJS,ClassDeclarations)925 TEST_F(FormatTestJS, ClassDeclarations) {
926 verifyFormat("class C {\n x: string = 12;\n}");
927 verifyFormat("class C {\n x(): string => 12;\n}");
928 verifyFormat("class C {\n ['x' + 2]: string = 12;\n}");
929 verifyFormat("class C {\n private x: string = 12;\n}");
930 verifyFormat("class C {\n private static x: string = 12;\n}");
931 verifyFormat("class C {\n static x(): string { return 'asd'; }\n}");
932 verifyFormat("class C extends P implements I {}");
933 verifyFormat("class C extends p.P implements i.I {}");
934 verifyFormat("class Test {\n"
935 " aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
936 " aaaaaaaaaaaaaaaaaaaaaa {}\n"
937 "}");
938 verifyFormat("foo = class Name {\n"
939 " constructor() {}\n"
940 "};");
941 verifyFormat("foo = class {\n"
942 " constructor() {}\n"
943 "};");
944 verifyFormat("class C {\n"
945 " x: {y: Z;} = {};\n"
946 " private y: {y: Z;} = {};\n"
947 "}");
948
949 // ':' is not a type declaration here.
950 verifyFormat("class X {\n"
951 " subs = {\n"
952 " 'b': {\n"
953 " 'c': 1,\n"
954 " },\n"
955 " };\n"
956 "}");
957 verifyFormat("@Component({\n"
958 " moduleId: module.id,\n"
959 "})\n"
960 "class SessionListComponent implements OnDestroy, OnInit {\n"
961 "}");
962 }
963
TEST_F(FormatTestJS,InterfaceDeclarations)964 TEST_F(FormatTestJS, InterfaceDeclarations) {
965 verifyFormat("interface I {\n"
966 " x: string;\n"
967 " enum: string[];\n"
968 " enum?: string[];\n"
969 "}\n"
970 "var y;");
971 // Ensure that state is reset after parsing the interface.
972 verifyFormat("interface a {}\n"
973 "export function b() {}\n"
974 "var x;");
975
976 // Arrays of object type literals.
977 verifyFormat("interface I {\n"
978 " o: {}[];\n"
979 "}");
980 }
981
TEST_F(FormatTestJS,EnumDeclarations)982 TEST_F(FormatTestJS, EnumDeclarations) {
983 verifyFormat("enum Foo {\n"
984 " A = 1,\n"
985 " B\n"
986 "}");
987 verifyFormat("export /* somecomment*/ enum Foo {\n"
988 " A = 1,\n"
989 " B\n"
990 "}");
991 verifyFormat("enum Foo {\n"
992 " A = 1, // comment\n"
993 " B\n"
994 "}\n"
995 "var x = 1;");
996 }
997
TEST_F(FormatTestJS,MetadataAnnotations)998 TEST_F(FormatTestJS, MetadataAnnotations) {
999 verifyFormat("@A\nclass C {\n}");
1000 verifyFormat("@A({arg: 'value'})\nclass C {\n}");
1001 verifyFormat("@A\n@B\nclass C {\n}");
1002 verifyFormat("class C {\n @A x: string;\n}");
1003 verifyFormat("class C {\n"
1004 " @A\n"
1005 " private x(): string {\n"
1006 " return 'y';\n"
1007 " }\n"
1008 "}");
1009 verifyFormat("class C {\n"
1010 " private x(@A x: string) {}\n"
1011 "}");
1012 verifyFormat("class X {}\n"
1013 "class Y {}");
1014 }
1015
TEST_F(FormatTestJS,TypeAliases)1016 TEST_F(FormatTestJS, TypeAliases) {
1017 verifyFormat("type X = number;\n"
1018 "class C {}");
1019 verifyFormat("type X<Y> = Z<Y>;");
1020 verifyFormat("type X = {\n"
1021 " y: number\n"
1022 "};\n"
1023 "class C {}");
1024 }
1025
TEST_F(FormatTestJS,Modules)1026 TEST_F(FormatTestJS, Modules) {
1027 verifyFormat("import SomeThing from 'some/module.js';");
1028 verifyFormat("import {X, Y} from 'some/module.js';");
1029 verifyFormat("import a, {X, Y} from 'some/module.js';");
1030 verifyFormat("import {X, Y,} from 'some/module.js';");
1031 verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
1032 // Ensure Automatic Semicolon Insertion does not break on "as\n".
1033 verifyFormat("import {X as myX} from 'm';", "import {X as\n"
1034 " myX} from 'm';");
1035 verifyFormat("import * as lib from 'some/module.js';");
1036 verifyFormat("var x = {import: 1};\nx.import = 2;");
1037
1038 verifyFormat("export function fn() {\n"
1039 " return 'fn';\n"
1040 "}");
1041 verifyFormat("export function A() {}\n"
1042 "export default function B() {}\n"
1043 "export function C() {}");
1044 verifyFormat("export default () => {\n"
1045 " let x = 1;\n"
1046 " return x;\n"
1047 "}");
1048 verifyFormat("export const x = 12;");
1049 verifyFormat("export default class X {}");
1050 verifyFormat("export {X, Y} from 'some/module.js';");
1051 verifyFormat("export {X, Y,} from 'some/module.js';");
1052 verifyFormat("export {SomeVeryLongExport as X, "
1053 "SomeOtherVeryLongExport as Y} from 'some/module.js';");
1054 // export without 'from' is wrapped.
1055 verifyFormat("export let someRatherLongVariableName =\n"
1056 " someSurprisinglyLongVariable + someOtherRatherLongVar;");
1057 // ... but not if from is just an identifier.
1058 verifyFormat("export {\n"
1059 " from as from,\n"
1060 " someSurprisinglyLongVariable as\n"
1061 " from\n"
1062 "};",
1063 getGoogleJSStyleWithColumns(20));
1064 verifyFormat("export class C {\n"
1065 " x: number;\n"
1066 " y: string;\n"
1067 "}");
1068 verifyFormat("export class X { y: number; }");
1069 verifyFormat("export abstract class X { y: number; }");
1070 verifyFormat("export default class X { y: number }");
1071 verifyFormat("export default function() {\n return 1;\n}");
1072 verifyFormat("export var x = 12;");
1073 verifyFormat("class C {}\n"
1074 "export function f() {}\n"
1075 "var v;");
1076 verifyFormat("export var x: number = 12;");
1077 verifyFormat("export const y = {\n"
1078 " a: 1,\n"
1079 " b: 2\n"
1080 "};");
1081 verifyFormat("export enum Foo {\n"
1082 " BAR,\n"
1083 " // adsdasd\n"
1084 " BAZ\n"
1085 "}");
1086 verifyFormat("export default [\n"
1087 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1088 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
1089 "];");
1090 verifyFormat("export default [];");
1091 verifyFormat("export default () => {};");
1092 verifyFormat("export interface Foo { foo: number; }\n"
1093 "export class Bar {\n"
1094 " blah(): string { return this.blah; };\n"
1095 "}");
1096 }
1097
TEST_F(FormatTestJS,ImportWrapping)1098 TEST_F(FormatTestJS, ImportWrapping) {
1099 verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
1100 " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
1101 "} from 'some/module.js';");
1102 FormatStyle Style = getGoogleJSStyleWithColumns(80);
1103 Style.JavaScriptWrapImports = true;
1104 verifyFormat("import {\n"
1105 " VeryLongImportsAreAnnoying,\n"
1106 " VeryLongImportsAreAnnoying,\n"
1107 " VeryLongImportsAreAnnoying,\n"
1108 "} from 'some/module.js';",
1109 Style);
1110 verifyFormat("import {\n"
1111 " A,\n"
1112 " A,\n"
1113 "} from 'some/module.js';",
1114 Style);
1115 verifyFormat("export {\n"
1116 " A,\n"
1117 " A,\n"
1118 "} from 'some/module.js';",
1119 Style);
1120 }
1121
TEST_F(FormatTestJS,TemplateStrings)1122 TEST_F(FormatTestJS, TemplateStrings) {
1123 // Keeps any whitespace/indentation within the template string.
1124 verifyFormat("var x = `hello\n"
1125 " ${ name }\n"
1126 " !`;",
1127 "var x = `hello\n"
1128 " ${ name }\n"
1129 " !`;");
1130
1131 verifyFormat("var x =\n"
1132 " `hello ${world}` >= some();",
1133 getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
1134 verifyFormat("var x = `hello ${world}` >= some();",
1135 getGoogleJSStyleWithColumns(35)); // Barely fits.
1136 verifyFormat("var x = `hellö ${wörld}` >= söme();",
1137 getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8.
1138 verifyFormat("var x = `hello\n"
1139 " ${world}` >=\n"
1140 " some();",
1141 "var x =\n"
1142 " `hello\n"
1143 " ${world}` >= some();",
1144 getGoogleJSStyleWithColumns(21)); // Barely doesn't fit.
1145 verifyFormat("var x = `hello\n"
1146 " ${world}` >= some();",
1147 "var x =\n"
1148 " `hello\n"
1149 " ${world}` >= some();",
1150 getGoogleJSStyleWithColumns(22)); // Barely fits.
1151
1152 verifyFormat("var x =\n"
1153 " `h`;",
1154 getGoogleJSStyleWithColumns(11));
1155 verifyFormat("var x =\n `multi\n line`;", "var x = `multi\n line`;",
1156 getGoogleJSStyleWithColumns(13));
1157 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1158 " `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
1159 // Repro for an obscure width-miscounting issue with template strings.
1160 verifyFormat(
1161 "someLongVariable =\n"
1162 " "
1163 "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;",
1164 "someLongVariable = "
1165 "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;");
1166
1167 // Make sure template strings get a proper ColumnWidth assigned, even if they
1168 // are first token in line.
1169 verifyFormat(
1170 "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1171 " `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
1172
1173 // Two template strings.
1174 verifyFormat("var x = `hello` == `hello`;");
1175
1176 // Comments in template strings.
1177 verifyFormat("var x = `//a`;\n"
1178 "var y;",
1179 "var x =\n `//a`;\n"
1180 "var y ;");
1181 verifyFormat("var x = `/*a`;\n"
1182 "var y;",
1183 "var x =\n `/*a`;\n"
1184 "var y;");
1185 // Unterminated string literals in a template string.
1186 verifyFormat("var x = `'`; // comment with matching quote '\n"
1187 "var y;");
1188 verifyFormat("var x = `\"`; // comment with matching quote \"\n"
1189 "var y;");
1190 verifyFormat("it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa);",
1191 "it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa) ;",
1192 getGoogleJSStyleWithColumns(40));
1193 // Backticks in a comment - not a template string.
1194 verifyFormat("var x = 1 // `/*a`;\n"
1195 " ;",
1196 "var x =\n 1 // `/*a`;\n"
1197 " ;");
1198 verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */");
1199 // Comment spans multiple template strings.
1200 verifyFormat("var x = `/*a`;\n"
1201 "var y = ` */ `;",
1202 "var x =\n `/*a`;\n"
1203 "var y =\n ` */ `;");
1204 // Escaped backtick.
1205 verifyFormat("var x = ` \\` a`;\n"
1206 "var y;",
1207 "var x = ` \\` a`;\n"
1208 "var y;");
1209 }
1210
TEST_F(FormatTestJS,CastSyntax)1211 TEST_F(FormatTestJS, CastSyntax) {
1212 verifyFormat("var x = <type>foo;");
1213 verifyFormat("var x = foo as type;");
1214 verifyFormat("let x = (a + b) as\n"
1215 " LongTypeIsLong;",
1216 getGoogleJSStyleWithColumns(20));
1217 verifyFormat("foo = <Bar[]>[\n"
1218 " 1, //\n"
1219 " 2\n"
1220 "];");
1221 }
1222
TEST_F(FormatTestJS,TypeArguments)1223 TEST_F(FormatTestJS, TypeArguments) {
1224 verifyFormat("class X<Y> {}");
1225 verifyFormat("new X<Y>();");
1226 verifyFormat("foo<Y>(a);");
1227 verifyFormat("var x: X<Y>[];");
1228 verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
1229 verifyFormat("function f(a: List<any> = null) {}");
1230 verifyFormat("function f(): List<any> {}");
1231 verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
1232 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
1233 verifyFormat("function aaaaaaaaaa(\n"
1234 " aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
1235 " aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
1236 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
1237 }
1238
TEST_F(FormatTestJS,UserDefinedTypeGuards)1239 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
1240 verifyFormat(
1241 "function foo(check: Object):\n"
1242 " check is {foo: string, bar: string, baz: string, foobar: string} {\n"
1243 " return 'bar' in check;\n"
1244 "}\n");
1245 }
1246
TEST_F(FormatTestJS,OptionalTypes)1247 TEST_F(FormatTestJS, OptionalTypes) {
1248 verifyFormat("function x(a?: b, c?, d?) {}");
1249 verifyFormat("class X {\n"
1250 " y?: z;\n"
1251 " z?;\n"
1252 "}");
1253 verifyFormat("interface X {\n"
1254 " y?(): z;\n"
1255 "}");
1256 verifyFormat("constructor({aa}: {\n"
1257 " aa?: string,\n"
1258 " aaaaaaaa?: string,\n"
1259 " aaaaaaaaaaaaaaa?: boolean,\n"
1260 " aaaaaa?: List<string>\n"
1261 "}) {}");
1262 }
1263
TEST_F(FormatTestJS,IndexSignature)1264 TEST_F(FormatTestJS, IndexSignature) {
1265 verifyFormat("var x: {[k: string]: v};");
1266 }
1267
TEST_F(FormatTestJS,WrapAfterParen)1268 TEST_F(FormatTestJS, WrapAfterParen) {
1269 verifyFormat("xxxxxxxxxxx(\n"
1270 " aaa, aaa);",
1271 getGoogleJSStyleWithColumns(20));
1272 verifyFormat("xxxxxxxxxxx(\n"
1273 " aaa, aaa, aaa,\n"
1274 " aaa, aaa, aaa);",
1275 getGoogleJSStyleWithColumns(20));
1276 verifyFormat("xxxxxxxxxxx(\n"
1277 " aaaaaaaaaaaaaaaaaaaaaaaa,\n"
1278 " function(x) {\n"
1279 " y(); //\n"
1280 " });",
1281 getGoogleJSStyleWithColumns(40));
1282 verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
1283 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
1284 }
1285
TEST_F(FormatTestJS,JSDocAnnotations)1286 TEST_F(FormatTestJS, JSDocAnnotations) {
1287 verifyFormat("/**\n"
1288 " * @export {this.is.a.long.path.to.a.Type}\n"
1289 " */",
1290 "/**\n"
1291 " * @export {this.is.a.long.path.to.a.Type}\n"
1292 " */",
1293 getGoogleJSStyleWithColumns(20));
1294 }
1295
TEST_F(FormatTestJS,RequoteStringsSingle)1296 TEST_F(FormatTestJS, RequoteStringsSingle) {
1297 verifyFormat("var x = 'foo';", "var x = \"foo\";");
1298 verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";");
1299 verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";");
1300 verifyFormat(
1301 "var x =\n"
1302 " 'foo\\'';",
1303 // Code below is 15 chars wide, doesn't fit into the line with the
1304 // \ escape added.
1305 "var x = \"foo'\";", getGoogleJSStyleWithColumns(15));
1306 // Removes no-longer needed \ escape from ".
1307 verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";");
1308 // Code below fits into 15 chars *after* removing the \ escape.
1309 verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";",
1310 getGoogleJSStyleWithColumns(15));
1311 verifyFormat("// clang-format off\n"
1312 "let x = \"double\";\n"
1313 "// clang-format on\n"
1314 "let x = 'single';\n",
1315 "// clang-format off\n"
1316 "let x = \"double\";\n"
1317 "// clang-format on\n"
1318 "let x = \"single\";\n");
1319 }
1320
TEST_F(FormatTestJS,RequoteStringsDouble)1321 TEST_F(FormatTestJS, RequoteStringsDouble) {
1322 FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
1323 DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double;
1324 verifyFormat("var x = \"foo\";", DoubleQuotes);
1325 verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes);
1326 verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes);
1327 }
1328
TEST_F(FormatTestJS,RequoteStringsLeave)1329 TEST_F(FormatTestJS, RequoteStringsLeave) {
1330 FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
1331 LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave;
1332 verifyFormat("var x = \"foo\";", LeaveQuotes);
1333 verifyFormat("var x = 'foo';", LeaveQuotes);
1334 }
1335
TEST_F(FormatTestJS,SupportShebangLines)1336 TEST_F(FormatTestJS, SupportShebangLines) {
1337 verifyFormat("#!/usr/bin/env node\n"
1338 "var x = hello();",
1339 "#!/usr/bin/env node\n"
1340 "var x = hello();");
1341 }
1342
TEST_F(FormatTestJS,NonNullAssertionOperator)1343 TEST_F(FormatTestJS, NonNullAssertionOperator) {
1344 verifyFormat("let x = foo!.bar();\n");
1345 verifyFormat("let x = foo ? bar! : baz;\n");
1346 verifyFormat("let x = !foo;\n");
1347 verifyFormat("let x = foo[0]!;\n");
1348 verifyFormat("let x = (foo)!;\n");
1349 verifyFormat("let x = {foo: 1}!;\n");
1350 }
1351
TEST_F(FormatTestJS,Conditional)1352 TEST_F(FormatTestJS, Conditional) {
1353 verifyFormat("y = x ? 1 : 2;");
1354 verifyFormat("x ? 1 : 2;");
1355 verifyFormat("class Foo {\n"
1356 " field = true ? 1 : 2;\n"
1357 " method(a = true ? 1 : 2) {}\n"
1358 "}");
1359 }
1360
1361 } // end namespace tooling
1362 } // end namespace clang
1363