xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision d40bca431dfab7deae906fae9eea72dbdd81de2c)
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 = {a: 1}\n"
863       "class Y {}",
864       "  x  =  {a  : 1}\n"
865       "   class  Y {  }");
866 }
867 
868 TEST_F(FormatTestJS, ImportExportASI) {
869   verifyFormat(
870       "import {x} from 'y'\n"
871       "export function z() {}",
872       "import   {x} from 'y'\n"
873       "  export function z() {}");
874   verifyFormat(
875       "export {x}\n"
876       "class Y {}",
877       "  export {x}\n"
878       "  class  Y {\n}");
879 }
880 
881 TEST_F(FormatTestJS, ClosureStyleCasts) {
882   verifyFormat("var x = /** @type {foo} */ (bar);");
883 }
884 
885 TEST_F(FormatTestJS, TryCatch) {
886   verifyFormat("try {\n"
887                "  f();\n"
888                "} catch (e) {\n"
889                "  g();\n"
890                "} finally {\n"
891                "  h();\n"
892                "}");
893 
894   // But, of course, "catch" is a perfectly fine function name in JavaScript.
895   verifyFormat("someObject.catch();");
896   verifyFormat("someObject.new();");
897   verifyFormat("someObject.delete();");
898 }
899 
900 TEST_F(FormatTestJS, StringLiteralConcatenation) {
901   verifyFormat("var literal = 'hello ' +\n"
902                "    'world';");
903 }
904 
905 TEST_F(FormatTestJS, RegexLiteralClassification) {
906   // Regex literals.
907   verifyFormat("var regex = /abc/;");
908   verifyFormat("f(/abc/);");
909   verifyFormat("f(abc, /abc/);");
910   verifyFormat("some_map[/abc/];");
911   verifyFormat("var x = a ? /abc/ : /abc/;");
912   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
913   verifyFormat("var x = !/abc/.test(y);");
914   verifyFormat("var x = a && /abc/.test(y);");
915   verifyFormat("var x = a || /abc/.test(y);");
916   verifyFormat("var x = a + /abc/.search(y);");
917   verifyFormat("/abc/.search(y);");
918   verifyFormat("var regexs = {/abc/, /abc/};");
919   verifyFormat("return /abc/;");
920 
921   // Not regex literals.
922   verifyFormat("var a = a / 2 + b / 3;");
923   verifyFormat("var a = a++ / 2;");
924   // Prefix unary can operate on regex literals, not that it makes sense.
925   verifyFormat("var a = ++/a/;");
926 
927   // This is a known issue, regular expressions are incorrectly detected if
928   // directly following a closing parenthesis.
929   verifyFormat("if (foo) / bar /.exec(baz);");
930 }
931 
932 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
933   verifyFormat("var regex = /=/;");
934   verifyFormat("var regex = /a*/;");
935   verifyFormat("var regex = /a+/;");
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 = /(?:x)/;");
942   verifyFormat("var regex = /x(?=y)/;");
943   verifyFormat("var regex = /x(?!y)/;");
944   verifyFormat("var regex = /x|y/;");
945   verifyFormat("var regex = /a{2}/;");
946   verifyFormat("var regex = /a{1,3}/;");
947 
948   verifyFormat("var regex = /[abc]/;");
949   verifyFormat("var regex = /[^abc]/;");
950   verifyFormat("var regex = /[\\b]/;");
951   verifyFormat("var regex = /[/]/;");
952   verifyFormat("var regex = /[\\/]/;");
953   verifyFormat("var regex = /\\[/;");
954   verifyFormat("var regex = /\\\\[/]/;");
955   verifyFormat("var regex = /}[\"]/;");
956   verifyFormat("var regex = /}[/\"]/;");
957   verifyFormat("var regex = /}[\"/]/;");
958 
959   verifyFormat("var regex = /\\b/;");
960   verifyFormat("var regex = /\\B/;");
961   verifyFormat("var regex = /\\d/;");
962   verifyFormat("var regex = /\\D/;");
963   verifyFormat("var regex = /\\f/;");
964   verifyFormat("var regex = /\\n/;");
965   verifyFormat("var regex = /\\r/;");
966   verifyFormat("var regex = /\\s/;");
967   verifyFormat("var regex = /\\S/;");
968   verifyFormat("var regex = /\\t/;");
969   verifyFormat("var regex = /\\v/;");
970   verifyFormat("var regex = /\\w/;");
971   verifyFormat("var regex = /\\W/;");
972   verifyFormat("var regex = /a(a)\\1/;");
973   verifyFormat("var regex = /\\0/;");
974   verifyFormat("var regex = /\\\\/g;");
975   verifyFormat("var regex = /\\a\\\\/g;");
976   verifyFormat("var regex = /\a\\//g;");
977   verifyFormat("var regex = /a\\//;\n"
978                "var x = 0;");
979   verifyFormat("var regex = /'/g;", "var regex = /'/g ;");
980   verifyFormat("var regex = /'/g;  //'", "var regex = /'/g ; //'");
981   verifyFormat("var regex = /\\/*/;\n"
982                "var x = 0;",
983                "var regex = /\\/*/;\n"
984                "var x=0;");
985   verifyFormat("var x = /a\\//;", "var x = /a\\//  \n;");
986   verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
987   verifyFormat("var regex =\n"
988                "    /\"/;",
989                getGoogleJSStyleWithColumns(15));
990   verifyFormat("var regex =  //\n"
991                "    /a/;");
992   verifyFormat("var regexs = [\n"
993                "  /d/,   //\n"
994                "  /aa/,  //\n"
995                "];");
996 }
997 
998 TEST_F(FormatTestJS, RegexLiteralModifiers) {
999   verifyFormat("var regex = /abc/g;");
1000   verifyFormat("var regex = /abc/i;");
1001   verifyFormat("var regex = /abc/m;");
1002   verifyFormat("var regex = /abc/y;");
1003 }
1004 
1005 TEST_F(FormatTestJS, RegexLiteralLength) {
1006   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1007                getGoogleJSStyleWithColumns(60));
1008   verifyFormat("var regex =\n"
1009                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1010                getGoogleJSStyleWithColumns(60));
1011   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1012                getGoogleJSStyleWithColumns(50));
1013 }
1014 
1015 TEST_F(FormatTestJS, RegexLiteralExamples) {
1016   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
1017 }
1018 
1019 TEST_F(FormatTestJS, TypeAnnotations) {
1020   verifyFormat("var x: string;");
1021   verifyFormat("var x: {a: string; b: number;} = {};");
1022   verifyFormat("function x(): string {\n  return 'x';\n}");
1023   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
1024   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
1025   verifyFormat("for (var y: string in x) {\n  x();\n}");
1026   verifyFormat("for (var y: string of x) {\n  x();\n}");
1027   verifyFormat("function x(y: {a?: number;} = {}): number {\n"
1028                "  return 12;\n"
1029                "}");
1030   verifyFormat("((a: string, b: number): string => a + b);");
1031   verifyFormat("var x: (y: number) => string;");
1032   verifyFormat("var x: P<string, (a: number) => string>;");
1033   verifyFormat("var x = {\n"
1034                "  y: function(): z {\n"
1035                "    return 1;\n"
1036                "  }\n"
1037                "};");
1038   verifyFormat("var x = {\n"
1039                "  y: function(): {a: number} {\n"
1040                "    return 1;\n"
1041                "  }\n"
1042                "};");
1043   verifyFormat("function someFunc(args: string[]):\n"
1044                "    {longReturnValue: string[]} {}",
1045                getGoogleJSStyleWithColumns(60));
1046 }
1047 
1048 TEST_F(FormatTestJS, UnionIntersectionTypes) {
1049   verifyFormat("let x: A|B = A | B;");
1050   verifyFormat("let x: A&B|C = A & B;");
1051   verifyFormat("let x: Foo<A|B> = new Foo<A|B>();");
1052   verifyFormat("function(x: A|B): C&D {}");
1053   verifyFormat("function(x: A|B = A | B): C&D {}");
1054   verifyFormat("function x(path: number|string) {}");
1055   verifyFormat("function x(): string|number {}");
1056   verifyFormat("type Foo = Bar|Baz;");
1057   verifyFormat("type Foo = Bar<X>|Baz;");
1058   verifyFormat("type Foo = (Bar<X>|Baz);");
1059   verifyFormat("let x: Bar|Baz;");
1060   verifyFormat("let x: Bar<X>|Baz;");
1061   verifyFormat("let x: (Foo|Bar)[];");
1062 }
1063 
1064 TEST_F(FormatTestJS, ClassDeclarations) {
1065   verifyFormat("class C {\n  x: string = 12;\n}");
1066   verifyFormat("class C {\n  x(): string => 12;\n}");
1067   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
1068   verifyFormat("class C {\n  private x: string = 12;\n}");
1069   verifyFormat("class C {\n  private static x: string = 12;\n}");
1070   verifyFormat("class C {\n  static x(): string {\n    return 'asd';\n  }\n}");
1071   verifyFormat("class C extends P implements I {}");
1072   verifyFormat("class C extends p.P implements i.I {}");
1073   verifyFormat("class Test {\n"
1074                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
1075                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
1076                "}");
1077   verifyFormat("foo = class Name {\n"
1078                "  constructor() {}\n"
1079                "};");
1080   verifyFormat("foo = class {\n"
1081                "  constructor() {}\n"
1082                "};");
1083   verifyFormat("class C {\n"
1084                "  x: {y: Z;} = {};\n"
1085                "  private y: {y: Z;} = {};\n"
1086                "}");
1087 
1088   // ':' is not a type declaration here.
1089   verifyFormat("class X {\n"
1090                "  subs = {\n"
1091                "    'b': {\n"
1092                "      'c': 1,\n"
1093                "    },\n"
1094                "  };\n"
1095                "}");
1096   verifyFormat("@Component({\n"
1097                "  moduleId: module.id,\n"
1098                "})\n"
1099                "class SessionListComponent implements OnDestroy, OnInit {\n"
1100                "}");
1101 }
1102 
1103 TEST_F(FormatTestJS, InterfaceDeclarations) {
1104   verifyFormat("interface I {\n"
1105                "  x: string;\n"
1106                "  enum: string[];\n"
1107                "  enum?: string[];\n"
1108                "}\n"
1109                "var y;");
1110   // Ensure that state is reset after parsing the interface.
1111   verifyFormat("interface a {}\n"
1112                "export function b() {}\n"
1113                "var x;");
1114 
1115   // Arrays of object type literals.
1116   verifyFormat("interface I {\n"
1117                "  o: {}[];\n"
1118                "}");
1119 }
1120 
1121 TEST_F(FormatTestJS, EnumDeclarations) {
1122   verifyFormat("enum Foo {\n"
1123                "  A = 1,\n"
1124                "  B\n"
1125                "}");
1126   verifyFormat("export /* somecomment*/ enum Foo {\n"
1127                "  A = 1,\n"
1128                "  B\n"
1129                "}");
1130   verifyFormat("enum Foo {\n"
1131                "  A = 1,  // comment\n"
1132                "  B\n"
1133                "}\n"
1134                "var x = 1;");
1135 }
1136 
1137 TEST_F(FormatTestJS, MetadataAnnotations) {
1138   verifyFormat("@A\nclass C {\n}");
1139   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
1140   verifyFormat("@A\n@B\nclass C {\n}");
1141   verifyFormat("class C {\n  @A x: string;\n}");
1142   verifyFormat("class C {\n"
1143                "  @A\n"
1144                "  private x(): string {\n"
1145                "    return 'y';\n"
1146                "  }\n"
1147                "}");
1148   verifyFormat("class C {\n"
1149                "  private x(@A x: string) {}\n"
1150                "}");
1151   verifyFormat("class X {}\n"
1152                "class Y {}");
1153 }
1154 
1155 TEST_F(FormatTestJS, TypeAliases) {
1156   verifyFormat("type X = number;\n"
1157                "class C {}");
1158   verifyFormat("type X<Y> = Z<Y>;");
1159   verifyFormat("type X = {\n"
1160                "  y: number\n"
1161                "};\n"
1162                "class C {}");
1163 }
1164 
1165 TEST_F(FormatTestJS, Modules) {
1166   verifyFormat("import SomeThing from 'some/module.js';");
1167   verifyFormat("import {X, Y} from 'some/module.js';");
1168   verifyFormat("import a, {X, Y} from 'some/module.js';");
1169   verifyFormat("import {X, Y,} from 'some/module.js';");
1170   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
1171   // Ensure Automatic Semicolon Insertion does not break on "as\n".
1172   verifyFormat("import {X as myX} from 'm';", "import {X as\n"
1173                                               " myX} from 'm';");
1174   verifyFormat("import * as lib from 'some/module.js';");
1175   verifyFormat("var x = {import: 1};\nx.import = 2;");
1176 
1177   verifyFormat("export function fn() {\n"
1178                "  return 'fn';\n"
1179                "}");
1180   verifyFormat("export function A() {}\n"
1181                "export default function B() {}\n"
1182                "export function C() {}");
1183   verifyFormat("export default () => {\n"
1184                "  let x = 1;\n"
1185                "  return x;\n"
1186                "}");
1187   verifyFormat("export const x = 12;");
1188   verifyFormat("export default class X {}");
1189   verifyFormat("export {X, Y} from 'some/module.js';");
1190   verifyFormat("export {X, Y,} from 'some/module.js';");
1191   verifyFormat("export {SomeVeryLongExport as X, "
1192                "SomeOtherVeryLongExport as Y} from 'some/module.js';");
1193   // export without 'from' is wrapped.
1194   verifyFormat("export let someRatherLongVariableName =\n"
1195                "    someSurprisinglyLongVariable + someOtherRatherLongVar;");
1196   // ... but not if from is just an identifier.
1197   verifyFormat("export {\n"
1198                "  from as from,\n"
1199                "  someSurprisinglyLongVariable as\n"
1200                "      from\n"
1201                "};",
1202                getGoogleJSStyleWithColumns(20));
1203   verifyFormat("export class C {\n"
1204                "  x: number;\n"
1205                "  y: string;\n"
1206                "}");
1207   verifyFormat("export class X { y: number; }");
1208   verifyFormat("export abstract class X { y: number; }");
1209   verifyFormat("export default class X { y: number }");
1210   verifyFormat("export default function() {\n  return 1;\n}");
1211   verifyFormat("export var x = 12;");
1212   verifyFormat("class C {}\n"
1213                "export function f() {}\n"
1214                "var v;");
1215   verifyFormat("export var x: number = 12;");
1216   verifyFormat("export const y = {\n"
1217                "  a: 1,\n"
1218                "  b: 2\n"
1219                "};");
1220   verifyFormat("export enum Foo {\n"
1221                "  BAR,\n"
1222                "  // adsdasd\n"
1223                "  BAZ\n"
1224                "}");
1225   verifyFormat("export default [\n"
1226                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1227                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
1228                "];");
1229   verifyFormat("export default [];");
1230   verifyFormat("export default () => {};");
1231   verifyFormat("export interface Foo { foo: number; }\n"
1232                "export class Bar {\n"
1233                "  blah(): string {\n"
1234                "    return this.blah;\n"
1235                "  };\n"
1236                "}");
1237 }
1238 
1239 TEST_F(FormatTestJS, ImportWrapping) {
1240   verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
1241                " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
1242                "} from 'some/module.js';");
1243   FormatStyle Style = getGoogleJSStyleWithColumns(80);
1244   Style.JavaScriptWrapImports = true;
1245   verifyFormat("import {\n"
1246                "  VeryLongImportsAreAnnoying,\n"
1247                "  VeryLongImportsAreAnnoying,\n"
1248                "  VeryLongImportsAreAnnoying,\n"
1249                "} from 'some/module.js';",
1250                Style);
1251   verifyFormat("import {\n"
1252                "  A,\n"
1253                "  A,\n"
1254                "} from 'some/module.js';",
1255                Style);
1256   verifyFormat("export {\n"
1257                "  A,\n"
1258                "  A,\n"
1259                "} from 'some/module.js';",
1260                Style);
1261 }
1262 
1263 TEST_F(FormatTestJS, TemplateStrings) {
1264   // Keeps any whitespace/indentation within the template string.
1265   verifyFormat("var x = `hello\n"
1266             "     ${name}\n"
1267             "  !`;",
1268             "var x    =    `hello\n"
1269                    "     ${  name    }\n"
1270                    "  !`;");
1271 
1272   verifyFormat("var x =\n"
1273                "    `hello ${world}` >= some();",
1274                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
1275   verifyFormat("var x = `hello ${world}` >= some();",
1276                getGoogleJSStyleWithColumns(35)); // Barely fits.
1277   verifyFormat("var x = `hellö ${wörld}` >= söme();",
1278                getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8.
1279   verifyFormat("var x = `hello\n"
1280             "  ${world}` >=\n"
1281             "    some();",
1282             "var x =\n"
1283                    "    `hello\n"
1284                    "  ${world}` >= some();",
1285                    getGoogleJSStyleWithColumns(21)); // Barely doesn't fit.
1286   verifyFormat("var x = `hello\n"
1287             "  ${world}` >= some();",
1288             "var x =\n"
1289                    "    `hello\n"
1290                    "  ${world}` >= some();",
1291                    getGoogleJSStyleWithColumns(22)); // Barely fits.
1292 
1293   verifyFormat("var x =\n"
1294                "    `h`;",
1295                getGoogleJSStyleWithColumns(11));
1296   verifyFormat("var x =\n    `multi\n  line`;", "var x = `multi\n  line`;",
1297                getGoogleJSStyleWithColumns(13));
1298   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1299                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
1300   // Repro for an obscure width-miscounting issue with template strings.
1301   verifyFormat(
1302       "someLongVariable =\n"
1303       "    "
1304       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;",
1305       "someLongVariable = "
1306       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;");
1307 
1308   // Make sure template strings get a proper ColumnWidth assigned, even if they
1309   // are first token in line.
1310   verifyFormat(
1311       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1312       "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
1313 
1314   // Two template strings.
1315   verifyFormat("var x = `hello` == `hello`;");
1316 
1317   // Comments in template strings.
1318   verifyFormat("var x = `//a`;\n"
1319             "var y;",
1320             "var x =\n `//a`;\n"
1321                    "var y  ;");
1322   verifyFormat("var x = `/*a`;\n"
1323                "var y;",
1324                "var x =\n `/*a`;\n"
1325                "var y;");
1326   // Unterminated string literals in a template string.
1327   verifyFormat("var x = `'`;  // comment with matching quote '\n"
1328                "var y;");
1329   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
1330                "var y;");
1331   verifyFormat("it(`'aaaaaaaaaaaaaaa   `, aaaaaaaaa);",
1332                "it(`'aaaaaaaaaaaaaaa   `,   aaaaaaaaa) ;",
1333                getGoogleJSStyleWithColumns(40));
1334   // Backticks in a comment - not a template string.
1335   verifyFormat("var x = 1  // `/*a`;\n"
1336                "    ;",
1337                "var x =\n 1  // `/*a`;\n"
1338                "    ;");
1339   verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */");
1340   // Comment spans multiple template strings.
1341   verifyFormat("var x = `/*a`;\n"
1342                "var y = ` */ `;",
1343                "var x =\n `/*a`;\n"
1344                "var y =\n ` */ `;");
1345   // Escaped backtick.
1346   verifyFormat("var x = ` \\` a`;\n"
1347                "var y;",
1348                "var x = ` \\` a`;\n"
1349                "var y;");
1350   // Escaped dollar.
1351   verifyFormat("var x = ` \\${foo}`;\n");
1352 }
1353 
1354 TEST_F(FormatTestJS, TemplateStringASI) {
1355   verifyFormat("var x = `hello${world}`;", "var x = `hello${\n"
1356                                            "    world\n"
1357                                            "}`;");
1358 }
1359 
1360 TEST_F(FormatTestJS, NestedTemplateStrings) {
1361   verifyFormat(
1362       "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;");
1363   verifyFormat("var x = `he${({text: 'll'}.text)}o`;");
1364 
1365   // Crashed at some point.
1366   verifyFormat("}");
1367 }
1368 
1369 TEST_F(FormatTestJS, TaggedTemplateStrings) {
1370   verifyFormat("var x = html`<ul>`;");
1371 }
1372 
1373 TEST_F(FormatTestJS, CastSyntax) {
1374   verifyFormat("var x = <type>foo;");
1375   verifyFormat("var x = foo as type;");
1376   verifyFormat("let x = (a + b) as\n"
1377                "    LongTypeIsLong;",
1378                getGoogleJSStyleWithColumns(20));
1379   verifyFormat("foo = <Bar[]>[\n"
1380                "  1,  //\n"
1381                "  2\n"
1382                "];");
1383   verifyFormat("var x = [{x: 1} as type];");
1384   verifyFormat("x = x as [a, b];");
1385   verifyFormat("x = x as {a: string};");
1386   verifyFormat("x = x as (string);");
1387   verifyFormat("x = x! as (string);");
1388 }
1389 
1390 TEST_F(FormatTestJS, TypeArguments) {
1391   verifyFormat("class X<Y> {}");
1392   verifyFormat("new X<Y>();");
1393   verifyFormat("foo<Y>(a);");
1394   verifyFormat("var x: X<Y>[];");
1395   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
1396   verifyFormat("function f(a: List<any> = null) {}");
1397   verifyFormat("function f(): List<any> {}");
1398   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
1399                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
1400   verifyFormat("function aaaaaaaaaa(\n"
1401                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
1402                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
1403                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
1404 }
1405 
1406 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
1407   verifyFormat(
1408       "function foo(check: Object):\n"
1409       "    check is {foo: string, bar: string, baz: string, foobar: string} {\n"
1410       "  return 'bar' in check;\n"
1411       "}\n");
1412 }
1413 
1414 TEST_F(FormatTestJS, OptionalTypes) {
1415   verifyFormat("function x(a?: b, c?, d?) {}");
1416   verifyFormat("class X {\n"
1417                "  y?: z;\n"
1418                "  z?;\n"
1419                "}");
1420   verifyFormat("interface X {\n"
1421                "  y?(): z;\n"
1422                "}");
1423   verifyFormat("constructor({aa}: {\n"
1424                "  aa?: string,\n"
1425                "  aaaaaaaa?: string,\n"
1426                "  aaaaaaaaaaaaaaa?: boolean,\n"
1427                "  aaaaaa?: List<string>\n"
1428                "}) {}");
1429 }
1430 
1431 TEST_F(FormatTestJS, IndexSignature) {
1432   verifyFormat("var x: {[k: string]: v};");
1433 }
1434 
1435 TEST_F(FormatTestJS, WrapAfterParen) {
1436   verifyFormat("xxxxxxxxxxx(\n"
1437                "    aaa, aaa);",
1438                getGoogleJSStyleWithColumns(20));
1439   verifyFormat("xxxxxxxxxxx(\n"
1440                "    aaa, aaa, aaa,\n"
1441                "    aaa, aaa, aaa);",
1442                getGoogleJSStyleWithColumns(20));
1443   verifyFormat("xxxxxxxxxxx(\n"
1444                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
1445                "    function(x) {\n"
1446                "      y();  //\n"
1447                "    });",
1448                getGoogleJSStyleWithColumns(40));
1449   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
1450                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
1451 }
1452 
1453 TEST_F(FormatTestJS, JSDocAnnotations) {
1454   verifyFormat("/**\n"
1455                " * @export {this.is.a.long.path.to.a.Type}\n"
1456                " */",
1457                "/**\n"
1458                " * @export {this.is.a.long.path.to.a.Type}\n"
1459                " */",
1460                getGoogleJSStyleWithColumns(20));
1461 }
1462 
1463 TEST_F(FormatTestJS, RequoteStringsSingle) {
1464   verifyFormat("var x = 'foo';", "var x = \"foo\";");
1465   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";");
1466   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";");
1467   verifyFormat(
1468       "var x =\n"
1469       "    'foo\\'';",
1470       // Code below is 15 chars wide, doesn't fit into the line with the
1471       // \ escape added.
1472       "var x = \"foo'\";", getGoogleJSStyleWithColumns(15));
1473   // Removes no-longer needed \ escape from ".
1474   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";");
1475   // Code below fits into 15 chars *after* removing the \ escape.
1476   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";",
1477                getGoogleJSStyleWithColumns(15));
1478   verifyFormat("// clang-format off\n"
1479                "let x = \"double\";\n"
1480                "// clang-format on\n"
1481                "let x = 'single';\n",
1482                "// clang-format off\n"
1483                "let x = \"double\";\n"
1484                "// clang-format on\n"
1485                "let x = \"single\";\n");
1486 }
1487 
1488 TEST_F(FormatTestJS, RequoteAndIndent) {
1489   verifyFormat("let x = someVeryLongFunctionThatGoesOnAndOn(\n"
1490                "    'double quoted string that needs wrapping');",
1491                "let x = someVeryLongFunctionThatGoesOnAndOn("
1492                "\"double quoted string that needs wrapping\");");
1493 
1494   verifyFormat("let x =\n"
1495                "    'foo\\'oo';\n"
1496                "let x =\n"
1497                "    'foo\\'oo';",
1498                "let x=\"foo'oo\";\n"
1499                "let x=\"foo'oo\";",
1500                getGoogleJSStyleWithColumns(15));
1501 }
1502 
1503 TEST_F(FormatTestJS, RequoteStringsDouble) {
1504   FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
1505   DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double;
1506   verifyFormat("var x = \"foo\";", DoubleQuotes);
1507   verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes);
1508   verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes);
1509 }
1510 
1511 TEST_F(FormatTestJS, RequoteStringsLeave) {
1512   FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
1513   LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave;
1514   verifyFormat("var x = \"foo\";", LeaveQuotes);
1515   verifyFormat("var x = 'foo';", LeaveQuotes);
1516 }
1517 
1518 TEST_F(FormatTestJS, SupportShebangLines) {
1519   verifyFormat("#!/usr/bin/env node\n"
1520                "var x = hello();",
1521                "#!/usr/bin/env node\n"
1522                "var x   =  hello();");
1523 }
1524 
1525 TEST_F(FormatTestJS, NonNullAssertionOperator) {
1526   verifyFormat("let x = foo!.bar();\n");
1527   verifyFormat("let x = foo ? bar! : baz;\n");
1528   verifyFormat("let x = !foo;\n");
1529   verifyFormat("let x = foo[0]!;\n");
1530   verifyFormat("let x = (foo)!;\n");
1531   verifyFormat("let x = foo! - 1;\n");
1532   verifyFormat("let x = {foo: 1}!;\n");
1533 }
1534 
1535 TEST_F(FormatTestJS, Conditional) {
1536   verifyFormat("y = x ? 1 : 2;");
1537   verifyFormat("x ? 1 : 2;");
1538   verifyFormat("class Foo {\n"
1539                "  field = true ? 1 : 2;\n"
1540                "  method(a = true ? 1 : 2) {}\n"
1541                "}");
1542 }
1543 
1544 TEST_F(FormatTestJS, ImportComments) {
1545   verifyFormat("import {x} from 'x';  // from some location",
1546                getGoogleJSStyleWithColumns(25));
1547   verifyFormat("// taze: x from 'location'", getGoogleJSStyleWithColumns(10));
1548 }
1549 
1550 } // end namespace tooling
1551 } // end namespace clang
1552