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