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