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