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