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