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