xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision 1ce41112a43005b3ac2ee24119f2e633d86a27f5)
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     std::string Result = applyAllReplacements(Code, Replaces);
32     EXPECT_NE("", 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 
57 TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
58   verifyFormat("a == = b;");
59   verifyFormat("a != = b;");
60 
61   verifyFormat("a === b;");
62   verifyFormat("aaaaaaa ===\n    b;", getGoogleJSStyleWithColumns(10));
63   verifyFormat("a !== b;");
64   verifyFormat("aaaaaaa !==\n    b;", getGoogleJSStyleWithColumns(10));
65   verifyFormat("if (a + b + c +\n"
66                "        d !==\n"
67                "    e + f + g)\n"
68                "  q();",
69                getGoogleJSStyleWithColumns(20));
70 
71   verifyFormat("a >> >= b;");
72 
73   verifyFormat("a >>> b;");
74   verifyFormat("aaaaaaa >>>\n    b;", getGoogleJSStyleWithColumns(10));
75   verifyFormat("a >>>= b;");
76   verifyFormat("aaaaaaa >>>=\n    b;", getGoogleJSStyleWithColumns(10));
77   verifyFormat("if (a + b + c +\n"
78                "        d >>>\n"
79                "    e + f + g)\n"
80                "  q();",
81                getGoogleJSStyleWithColumns(20));
82   verifyFormat("var x = aaaaaaaaaa ?\n"
83                "    bbbbbb :\n"
84                "    ccc;",
85                getGoogleJSStyleWithColumns(20));
86 
87   verifyFormat("var b = a.map((x) => x + 1);");
88   verifyFormat("return ('aaa') in bbbb;");
89   verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
90                "    aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
91   FormatStyle Style = getGoogleJSStyleWithColumns(80);
92   Style.AlignOperands = true;
93   verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
94                "        aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
95                Style);
96   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
97   verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa()\n"
98                "            in aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
99                Style);
100 
101   // ES6 spread operator.
102   verifyFormat("someFunction(...a);");
103   verifyFormat("var x = [1, ...a, 2];");
104 }
105 
106 TEST_F(FormatTestJS, UnderstandsAmpAmp) {
107   verifyFormat("e && e.SomeFunction();");
108 }
109 
110 TEST_F(FormatTestJS, LiteralOperatorsCanBeKeywords) {
111   verifyFormat("not.and.or.not_eq = 1;");
112 }
113 
114 TEST_F(FormatTestJS, ReservedWords) {
115   // JavaScript reserved words (aka keywords) are only illegal when used as
116   // Identifiers, but are legal as IdentifierNames.
117   verifyFormat("x.class.struct = 1;");
118   verifyFormat("x.case = 1;");
119   verifyFormat("x.interface = 1;");
120   verifyFormat("x = {\n"
121                "  a: 12,\n"
122                "  interface: 1,\n"
123                "  switch: 1,\n"
124                "};");
125   verifyFormat("var struct = 2;");
126   verifyFormat("var union = 2;");
127 }
128 
129 TEST_F(FormatTestJS, CppKeywords) {
130   // Make sure we don't mess stuff up because of C++ keywords.
131   verifyFormat("return operator && (aa);");
132 }
133 
134 TEST_F(FormatTestJS, ES6DestructuringAssignment) {
135   verifyFormat("var [a, b, c] = [1, 2, 3];");
136   verifyFormat("let [a, b, c] = [1, 2, 3];");
137   verifyFormat("var {a, b} = {a: 1, b: 2};");
138   verifyFormat("let {a, b} = {a: 1, b: 2};");
139 }
140 
141 TEST_F(FormatTestJS, ContainerLiterals) {
142   verifyFormat("var x = {y: function(a) { return a; }};");
143   verifyFormat("return {\n"
144                "  link: function() {\n"
145                "    f();  //\n"
146                "  }\n"
147                "};");
148   verifyFormat("return {\n"
149                "  a: a,\n"
150                "  link: function() {\n"
151                "    f();  //\n"
152                "  }\n"
153                "};");
154   verifyFormat("return {\n"
155                "  a: a,\n"
156                "  link: function() {\n"
157                "    f();  //\n"
158                "  },\n"
159                "  link: function() {\n"
160                "    f();  //\n"
161                "  }\n"
162                "};");
163   verifyFormat("var stuff = {\n"
164                "  // comment for update\n"
165                "  update: false,\n"
166                "  // comment for modules\n"
167                "  modules: false,\n"
168                "  // comment for tasks\n"
169                "  tasks: false\n"
170                "};");
171   verifyFormat("return {\n"
172                "  'finish':\n"
173                "      //\n"
174                "      a\n"
175                "};");
176   verifyFormat("var obj = {\n"
177                "  fooooooooo: function(x) {\n"
178                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
179                "  }\n"
180                "};");
181   // Simple object literal, as opposed to enum style below.
182   verifyFormat("var obj = {a: 123};");
183   // Enum style top level assignment.
184   verifyFormat("X = {\n  a: 123\n};");
185   verifyFormat("X.Y = {\n  a: 123\n};");
186   // But only on the top level, otherwise its a plain object literal assignment.
187   verifyFormat("function x() {\n"
188                "  y = {z: 1};\n"
189                "}");
190   verifyFormat("x = foo && {a: 123};");
191 
192   // Arrow functions in object literals.
193   verifyFormat("var x = {y: (a) => { return a; }};");
194   verifyFormat("var x = {y: (a) => a};");
195 
196   // Computed keys.
197   verifyFormat("var x = {[a]: 1, b: 2, [c]: 3};");
198   verifyFormat("var x = {\n"
199                "  [a]: 1,\n"
200                "  b: 2,\n"
201                "  [c]: 3,\n"
202                "};");
203 }
204 
205 TEST_F(FormatTestJS, MethodsInObjectLiterals) {
206   verifyFormat("var o = {\n"
207                "  value: 'test',\n"
208                "  get value() {  // getter\n"
209                "    return this.value;\n"
210                "  }\n"
211                "};");
212   verifyFormat("var o = {\n"
213                "  value: 'test',\n"
214                "  set value(val) {  // setter\n"
215                "    this.value = val;\n"
216                "  }\n"
217                "};");
218   verifyFormat("var o = {\n"
219                "  value: 'test',\n"
220                "  someMethod(val) {  // method\n"
221                "    doSomething(this.value + val);\n"
222                "  }\n"
223                "};");
224   verifyFormat("var o = {\n"
225                "  someMethod(val) {  // method\n"
226                "    doSomething(this.value + val);\n"
227                "  },\n"
228                "  someOtherMethod(val) {  // method\n"
229                "    doSomething(this.value + val);\n"
230                "  }\n"
231                "};");
232 }
233 
234 TEST_F(FormatTestJS, SpacesInContainerLiterals) {
235   verifyFormat("var arr = [1, 2, 3];");
236   verifyFormat("f({a: 1, b: 2, c: 3});");
237 
238   verifyFormat("var object_literal_with_long_name = {\n"
239                "  a: 'aaaaaaaaaaaaaaaaaa',\n"
240                "  b: 'bbbbbbbbbbbbbbbbbb'\n"
241                "};");
242 
243   verifyFormat("f({a: 1, b: 2, c: 3});",
244                getChromiumStyle(FormatStyle::LK_JavaScript));
245   verifyFormat("f({'a': [{}]});");
246 }
247 
248 TEST_F(FormatTestJS, SingleQuoteStrings) {
249   verifyFormat("this.function('', true);");
250 }
251 
252 TEST_F(FormatTestJS, GoogScopes) {
253   verifyFormat("goog.scope(function() {\n"
254                "var x = a.b;\n"
255                "var y = c.d;\n"
256                "});  // goog.scope");
257   verifyFormat("goog.scope(function() {\n"
258                "// test\n"
259                "var x = 0;\n"
260                "// test\n"
261                "});");
262 }
263 
264 TEST_F(FormatTestJS, GoogModules) {
265   verifyFormat("goog.module('this.is.really.absurdly.long');",
266                getGoogleJSStyleWithColumns(40));
267   verifyFormat("goog.require('this.is.really.absurdly.long');",
268                getGoogleJSStyleWithColumns(40));
269   verifyFormat("goog.provide('this.is.really.absurdly.long');",
270                getGoogleJSStyleWithColumns(40));
271   verifyFormat("var long = goog.require('this.is.really.absurdly.long');",
272                getGoogleJSStyleWithColumns(40));
273   verifyFormat("goog.setTestOnly('this.is.really.absurdly.long');",
274                getGoogleJSStyleWithColumns(40));
275 
276   // These should be wrapped normally.
277   verifyFormat(
278       "var MyLongClassName =\n"
279       "    goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
280 }
281 
282 TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
283   verifyFormat("function outer1(a, b) {\n"
284                "  function inner1(a, b) { return a; }\n"
285                "  inner1(a, b);\n"
286                "}\n"
287                "function outer2(a, b) {\n"
288                "  function inner2(a, b) { return a; }\n"
289                "  inner2(a, b);\n"
290                "}");
291   verifyFormat("function f() {}");
292 }
293 
294 TEST_F(FormatTestJS, ArrayLiterals) {
295   verifyFormat("var aaaaa: List<SomeThing> =\n"
296                "    [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];");
297   verifyFormat("return [\n"
298                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
299                "  ccccccccccccccccccccccccccc\n"
300                "];");
301   verifyFormat("return [\n"
302                "  aaaa().bbbbbbbb('A'),\n"
303                "  aaaa().bbbbbbbb('B'),\n"
304                "  aaaa().bbbbbbbb('C'),\n"
305                "];");
306   verifyFormat("var someVariable = SomeFunction([\n"
307                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
308                "  ccccccccccccccccccccccccccc\n"
309                "]);");
310   verifyFormat("var someVariable = SomeFunction([\n"
311                "  [aaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbb],\n"
312                "]);",
313                getGoogleJSStyleWithColumns(51));
314   verifyFormat("var someVariable = SomeFunction(aaaa, [\n"
315                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
316                "  ccccccccccccccccccccccccccc\n"
317                "]);");
318   verifyFormat("var someVariable = SomeFunction(\n"
319                "    aaaa,\n"
320                "    [\n"
321                "      aaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
322                "      cccccccccccccccccccccccccc\n"
323                "    ],\n"
324                "    aaaa);");
325   verifyFormat("var aaaa = aaaaa ||  // wrap\n"
326                "    [];");
327 
328   verifyFormat("someFunction([], {a: a});");
329 }
330 
331 TEST_F(FormatTestJS, ColumnLayoutForArrayLiterals) {
332   verifyFormat("var array = [\n"
333                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
334                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
335                "];");
336   verifyFormat("var array = someFunction([\n"
337                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
338                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
339                "]);");
340 }
341 
342 TEST_F(FormatTestJS, FunctionLiterals) {
343   verifyFormat("doFoo(function() {});");
344   verifyFormat("doFoo(function() { return 1; });");
345   verifyFormat("var func = function() {\n"
346                "  return 1;\n"
347                "};");
348   verifyFormat("var func =  //\n"
349                "    function() {\n"
350                "  return 1;\n"
351                "};");
352   verifyFormat("return {\n"
353                "  body: {\n"
354                "    setAttribute: function(key, val) { this[key] = val; },\n"
355                "    getAttribute: function(key) { return this[key]; },\n"
356                "    style: {direction: ''}\n"
357                "  }\n"
358                "};");
359   verifyFormat("abc = xyz ? function() {\n"
360                "  return 1;\n"
361                "} : function() {\n"
362                "  return -1;\n"
363                "};");
364 
365   verifyFormat("var closure = goog.bind(\n"
366                "    function() {  // comment\n"
367                "      foo();\n"
368                "      bar();\n"
369                "    },\n"
370                "    this, arg1IsReallyLongAndNeeedsLineBreaks,\n"
371                "    arg3IsReallyLongAndNeeedsLineBreaks);");
372   verifyFormat("var closure = goog.bind(function() {  // comment\n"
373                "  foo();\n"
374                "  bar();\n"
375                "}, this);");
376   verifyFormat("return {\n"
377                "  a: 'E',\n"
378                "  b: function() {\n"
379                "    return function() {\n"
380                "      f();  //\n"
381                "    };\n"
382                "  }\n"
383                "};");
384   verifyFormat("{\n"
385                "  var someVariable = function(x) {\n"
386                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
387                "  };\n"
388                "}");
389   verifyFormat("someLooooooooongFunction(\n"
390                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
391                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
392                "    function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
393                "      // code\n"
394                "    });");
395 
396   verifyFormat("f({a: function() { return 1; }});",
397                getGoogleJSStyleWithColumns(33));
398   verifyFormat("f({\n"
399                "  a: function() { return 1; }\n"
400                "});",
401                getGoogleJSStyleWithColumns(32));
402 
403   verifyFormat("return {\n"
404                "  a: function SomeFunction() {\n"
405                "    // ...\n"
406                "    return 1;\n"
407                "  }\n"
408                "};");
409   verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
410                "    .then(goog.bind(function(aaaaaaaaaaa) {\n"
411                "      someFunction();\n"
412                "      someFunction();\n"
413                "    }, this), aaaaaaaaaaaaaaaaa);");
414 
415   verifyFormat("someFunction(goog.bind(function() {\n"
416                "  doSomething();\n"
417                "  doSomething();\n"
418                "}, this), goog.bind(function() {\n"
419                "  doSomething();\n"
420                "  doSomething();\n"
421                "}, this));");
422 
423   // FIXME: This is bad, we should be wrapping before "function() {".
424   verifyFormat("someFunction(function() {\n"
425                "  doSomething();  // break\n"
426                "})\n"
427                "    .doSomethingElse(\n"
428                "        // break\n"
429                "        );");
430 }
431 
432 TEST_F(FormatTestJS, InliningFunctionLiterals) {
433   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
434   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
435   verifyFormat("var func = function() {\n"
436                "  return 1;\n"
437                "};",
438                Style);
439   verifyFormat("var func = doSomething(function() { return 1; });", Style);
440   verifyFormat("var outer = function() {\n"
441                "  var inner = function() { return 1; }\n"
442                "};",
443                Style);
444   verifyFormat("function outer1(a, b) {\n"
445                "  function inner1(a, b) { return a; }\n"
446                "}",
447                Style);
448 
449   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
450   verifyFormat("var func = function() { return 1; };", Style);
451   verifyFormat("var func = doSomething(function() { return 1; });", Style);
452   verifyFormat(
453       "var outer = function() { var inner = function() { return 1; } };",
454       Style);
455   verifyFormat("function outer1(a, b) {\n"
456                "  function inner1(a, b) { return a; }\n"
457                "}",
458                Style);
459 
460   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
461   verifyFormat("var func = function() {\n"
462                "  return 1;\n"
463                "};",
464                Style);
465   verifyFormat("var func = doSomething(function() {\n"
466                "  return 1;\n"
467                "});",
468                Style);
469   verifyFormat("var outer = function() {\n"
470                "  var inner = function() {\n"
471                "    return 1;\n"
472                "  }\n"
473                "};",
474                Style);
475   verifyFormat("function outer1(a, b) {\n"
476                "  function inner1(a, b) {\n"
477                "    return a;\n"
478                "  }\n"
479                "}",
480                Style);
481 
482   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
483   verifyFormat("var func = function() {\n"
484                "  return 1;\n"
485                "};",
486                Style);
487 }
488 
489 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
490   verifyFormat("promise.then(\n"
491                "    function success() {\n"
492                "      doFoo();\n"
493                "      doBar();\n"
494                "    },\n"
495                "    function error() {\n"
496                "      doFoo();\n"
497                "      doBaz();\n"
498                "    },\n"
499                "    []);\n");
500   verifyFormat("promise.then(\n"
501                "    function success() {\n"
502                "      doFoo();\n"
503                "      doBar();\n"
504                "    },\n"
505                "    [],\n"
506                "    function error() {\n"
507                "      doFoo();\n"
508                "      doBaz();\n"
509                "    });\n");
510   verifyFormat("promise.then(\n"
511                "    [],\n"
512                "    function success() {\n"
513                "      doFoo();\n"
514                "      doBar();\n"
515                "    },\n"
516                "    function error() {\n"
517                "      doFoo();\n"
518                "      doBaz();\n"
519                "    });\n");
520 
521   verifyFormat("getSomeLongPromise()\n"
522                "    .then(function(value) { body(); })\n"
523                "    .thenCatch(function(error) {\n"
524                "      body();\n"
525                "      body();\n"
526                "    });");
527   verifyFormat("getSomeLongPromise()\n"
528                "    .then(function(value) {\n"
529                "      body();\n"
530                "      body();\n"
531                "    })\n"
532                "    .thenCatch(function(error) {\n"
533                "      body();\n"
534                "      body();\n"
535                "    });");
536 
537   verifyFormat("getSomeLongPromise()\n"
538                "    .then(function(value) { body(); })\n"
539                "    .thenCatch(function(error) { body(); });");
540 
541   verifyFormat("return [aaaaaaaaaaaaaaaaaaaaaa]\n"
542                "    .aaaaaaa(function() {\n"
543                "      //\n"
544                "    })\n"
545                "    .bbbbbb();");
546 }
547 
548 TEST_F(FormatTestJS, ArrowFunctions) {
549   verifyFormat("var x = (a) => {\n"
550                "  return a;\n"
551                "};");
552   verifyFormat("var x = (a) => {\n"
553                "  function y() { return 42; }\n"
554                "  return a;\n"
555                "};");
556   verifyFormat("var x = (a: type): {some: type} => {\n"
557                "  return a;\n"
558                "};");
559   verifyFormat("var x = (a) => a;");
560   verifyFormat("return () => [];");
561   verifyFormat("var aaaaaaaaaaaaaaaaaaaa = {\n"
562                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
563                "      (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
564                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) =>\n"
565                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
566                "};");
567   verifyFormat("var a = a.aaaaaaa(\n"
568                "    (a: a) => aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) &&\n"
569                "        aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
570   verifyFormat("var a = a.aaaaaaa(\n"
571                "    (a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) ?\n"
572                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb) :\n"
573                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
574 
575   // FIXME: This is bad, we should be wrapping before "() => {".
576   verifyFormat("someFunction(() => {\n"
577                "  doSomething();  // break\n"
578                "})\n"
579                "    .doSomethingElse(\n"
580                "        // break\n"
581                "        );");
582 }
583 
584 TEST_F(FormatTestJS, ReturnStatements) {
585   verifyFormat("function() {\n"
586                "  return [hello, world];\n"
587                "}");
588 }
589 
590 TEST_F(FormatTestJS, ForLoops) {
591   verifyFormat("for (var i in [2, 3]) {\n"
592                "}");
593 }
594 
595 TEST_F(FormatTestJS, AutomaticSemicolonInsertion) {
596   // The following statements must not wrap, as otherwise the program meaning
597   // would change due to automatic semicolon insertion.
598   // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
599   verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10));
600   verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10));
601   verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10));
602   verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
603   verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
604   verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
605   verifyFormat("return [\n"
606                "  aaa\n"
607                "];",
608                getGoogleJSStyleWithColumns(12));
609 }
610 
611 TEST_F(FormatTestJS, ClosureStyleCasts) {
612   verifyFormat("var x = /** @type {foo} */ (bar);");
613 }
614 
615 TEST_F(FormatTestJS, TryCatch) {
616   verifyFormat("try {\n"
617                "  f();\n"
618                "} catch (e) {\n"
619                "  g();\n"
620                "} finally {\n"
621                "  h();\n"
622                "}");
623 
624   // But, of course, "catch" is a perfectly fine function name in JavaScript.
625   verifyFormat("someObject.catch();");
626   verifyFormat("someObject.new();");
627   verifyFormat("someObject.delete();");
628 }
629 
630 TEST_F(FormatTestJS, StringLiteralConcatenation) {
631   verifyFormat("var literal = 'hello ' +\n"
632                "    'world';");
633 }
634 
635 TEST_F(FormatTestJS, RegexLiteralClassification) {
636   // Regex literals.
637   verifyFormat("var regex = /abc/;");
638   verifyFormat("f(/abc/);");
639   verifyFormat("f(abc, /abc/);");
640   verifyFormat("some_map[/abc/];");
641   verifyFormat("var x = a ? /abc/ : /abc/;");
642   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
643   verifyFormat("var x = !/abc/.test(y);");
644   verifyFormat("var x = a && /abc/.test(y);");
645   verifyFormat("var x = a || /abc/.test(y);");
646   verifyFormat("var x = a + /abc/.search(y);");
647   verifyFormat("/abc/.search(y);");
648   verifyFormat("var regexs = {/abc/, /abc/};");
649   verifyFormat("return /abc/;");
650 
651   // Not regex literals.
652   verifyFormat("var a = a / 2 + b / 3;");
653   verifyFormat("var a = a++ / 2;");
654   // Prefix unary can operate on regex literals, not that it makes sense.
655   verifyFormat("var a = ++/a/;");
656 
657   // This is a known issue, regular expressions are incorrectly detected if
658   // directly following a closing parenthesis.
659   verifyFormat("if (foo) / bar /.exec(baz);");
660 }
661 
662 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
663   verifyFormat("var regex = /=/;");
664   verifyFormat("var regex = /a*/;");
665   verifyFormat("var regex = /a+/;");
666   verifyFormat("var regex = /a?/;");
667   verifyFormat("var regex = /.a./;");
668   verifyFormat("var regex = /a\\*/;");
669   verifyFormat("var regex = /^a$/;");
670   verifyFormat("var regex = /\\/a/;");
671   verifyFormat("var regex = /(?:x)/;");
672   verifyFormat("var regex = /x(?=y)/;");
673   verifyFormat("var regex = /x(?!y)/;");
674   verifyFormat("var regex = /x|y/;");
675   verifyFormat("var regex = /a{2}/;");
676   verifyFormat("var regex = /a{1,3}/;");
677 
678   verifyFormat("var regex = /[abc]/;");
679   verifyFormat("var regex = /[^abc]/;");
680   verifyFormat("var regex = /[\\b]/;");
681   verifyFormat("var regex = /[/]/;");
682   verifyFormat("var regex = /[\\/]/;");
683   verifyFormat("var regex = /\\[/;");
684   verifyFormat("var regex = /\\\\[/]/;");
685   verifyFormat("var regex = /}[\"]/;");
686   verifyFormat("var regex = /}[/\"]/;");
687   verifyFormat("var regex = /}[\"/]/;");
688 
689   verifyFormat("var regex = /\\b/;");
690   verifyFormat("var regex = /\\B/;");
691   verifyFormat("var regex = /\\d/;");
692   verifyFormat("var regex = /\\D/;");
693   verifyFormat("var regex = /\\f/;");
694   verifyFormat("var regex = /\\n/;");
695   verifyFormat("var regex = /\\r/;");
696   verifyFormat("var regex = /\\s/;");
697   verifyFormat("var regex = /\\S/;");
698   verifyFormat("var regex = /\\t/;");
699   verifyFormat("var regex = /\\v/;");
700   verifyFormat("var regex = /\\w/;");
701   verifyFormat("var regex = /\\W/;");
702   verifyFormat("var regex = /a(a)\\1/;");
703   verifyFormat("var regex = /\\0/;");
704   verifyFormat("var regex = /\\\\/g;");
705   verifyFormat("var regex = /\\a\\\\/g;");
706   verifyFormat("var regex = /\a\\//g;");
707   verifyFormat("var regex = /a\\//;\n"
708                "var x = 0;");
709   EXPECT_EQ("var regex = /'/g;", format("var regex = /'/g ;"));
710   EXPECT_EQ("var regex = /'/g;  //'", format("var regex = /'/g ; //'"));
711   EXPECT_EQ("var regex = /\\/*/;\n"
712             "var x = 0;",
713             format("var regex = /\\/*/;\n"
714                    "var x=0;"));
715   EXPECT_EQ("var x = /a\\//;", format("var x = /a\\//  \n;"));
716   verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
717   verifyFormat("var regex =\n"
718                "    /\"/;",
719                getGoogleJSStyleWithColumns(15));
720   verifyFormat("var regex =  //\n"
721                "    /a/;");
722   verifyFormat("var regexs = [\n"
723                "  /d/,   //\n"
724                "  /aa/,  //\n"
725                "];");
726 }
727 
728 TEST_F(FormatTestJS, RegexLiteralModifiers) {
729   verifyFormat("var regex = /abc/g;");
730   verifyFormat("var regex = /abc/i;");
731   verifyFormat("var regex = /abc/m;");
732   verifyFormat("var regex = /abc/y;");
733 }
734 
735 TEST_F(FormatTestJS, RegexLiteralLength) {
736   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
737                getGoogleJSStyleWithColumns(60));
738   verifyFormat("var regex =\n"
739                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
740                getGoogleJSStyleWithColumns(60));
741   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
742                getGoogleJSStyleWithColumns(50));
743 }
744 
745 TEST_F(FormatTestJS, RegexLiteralExamples) {
746   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
747 }
748 
749 TEST_F(FormatTestJS, TypeAnnotations) {
750   verifyFormat("var x: string;");
751   verifyFormat("var x: {a: string; b: number;} = {};");
752   verifyFormat("function x(): string {\n  return 'x';\n}");
753   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
754   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
755   verifyFormat("for (var y: string in x) {\n  x();\n}");
756   verifyFormat("function x(y: {a?: number;} = {}): number {\n"
757                "  return 12;\n"
758                "}");
759   verifyFormat("((a: string, b: number): string => a + b);");
760   verifyFormat("var x: (y: number) => string;");
761   verifyFormat("var x: P<string, (a: number) => string>;");
762   verifyFormat("var x = {y: function(): z { return 1; }};");
763   verifyFormat("var x = {y: function(): {a: number} { return 1; }};");
764   verifyFormat("function someFunc(args: string[]):\n"
765                "    {longReturnValue: string[]} {}",
766                getGoogleJSStyleWithColumns(60));
767 }
768 
769 TEST_F(FormatTestJS, ClassDeclarations) {
770   verifyFormat("class C {\n  x: string = 12;\n}");
771   verifyFormat("class C {\n  x(): string => 12;\n}");
772   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
773   verifyFormat("class C {\n  private x: string = 12;\n}");
774   verifyFormat("class C {\n  private static x: string = 12;\n}");
775   verifyFormat("class C {\n  static x(): string { return 'asd'; }\n}");
776   verifyFormat("class C extends P implements I {}");
777   verifyFormat("class C extends p.P implements i.I {}");
778   verifyFormat("class Test {\n"
779                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
780                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
781                "}");
782   verifyFormat("foo = class Name {\n"
783                "  constructor() {}\n"
784                "};");
785   verifyFormat("foo = class {\n"
786                "  constructor() {}\n"
787                "};");
788   verifyFormat("class C {\n"
789                "  x: {y: Z;} = {};\n"
790                "  private y: {y: Z;} = {};\n"
791                "}");
792 
793   // ':' is not a type declaration here.
794   verifyFormat("class X {\n"
795                "  subs = {\n"
796                "    'b': {\n"
797                "      'c': 1,\n"
798                "    },\n"
799                "  };\n"
800                "}");
801 }
802 
803 TEST_F(FormatTestJS, InterfaceDeclarations) {
804   verifyFormat("interface I {\n"
805                "  x: string;\n"
806                "  enum: string[];\n"
807                "}\n"
808                "var y;");
809   // Ensure that state is reset after parsing the interface.
810   verifyFormat("interface a {}\n"
811                "export function b() {}\n"
812                "var x;");
813 
814   // Arrays of object type literals.
815   verifyFormat("interface I {\n"
816                "  o: {}[];\n"
817                "}");
818 }
819 
820 TEST_F(FormatTestJS, EnumDeclarations) {
821   verifyFormat("enum Foo {\n"
822                "  A = 1,\n"
823                "  B\n"
824                "}");
825   verifyFormat("export /* somecomment*/ enum Foo {\n"
826                "  A = 1,\n"
827                "  B\n"
828                "}");
829   verifyFormat("enum Foo {\n"
830                "  A = 1,  // comment\n"
831                "  B\n"
832                "}\n"
833                "var x = 1;");
834 }
835 
836 TEST_F(FormatTestJS, MetadataAnnotations) {
837   verifyFormat("@A\nclass C {\n}");
838   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
839   verifyFormat("@A\n@B\nclass C {\n}");
840   verifyFormat("class C {\n  @A x: string;\n}");
841   verifyFormat("class C {\n"
842                "  @A\n"
843                "  private x(): string {\n"
844                "    return 'y';\n"
845                "  }\n"
846                "}");
847   verifyFormat("class X {}\n"
848                "class Y {}");
849 }
850 
851 TEST_F(FormatTestJS, Modules) {
852   verifyFormat("import SomeThing from 'some/module.js';");
853   verifyFormat("import {X, Y} from 'some/module.js';");
854   verifyFormat("import a, {X, Y} from 'some/module.js';");
855   verifyFormat("import {\n"
856                "  VeryLongImportsAreAnnoying,\n"
857                "  VeryLongImportsAreAnnoying,\n"
858                "  VeryLongImportsAreAnnoying,\n"
859                "  VeryLongImportsAreAnnoying\n"
860                "} from 'some/module.js';");
861   verifyFormat("import {\n"
862                "  X,\n"
863                "  Y,\n"
864                "} from 'some/module.js';");
865   verifyFormat("import {\n"
866                "  X,\n"
867                "  Y,\n"
868                "} from 'some/long/module.js';",
869                getGoogleJSStyleWithColumns(20));
870   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
871   verifyFormat("import * as lib from 'some/module.js';");
872   verifyFormat("var x = {import: 1};\nx.import = 2;");
873 
874   verifyFormat("export function fn() {\n"
875                "  return 'fn';\n"
876                "}");
877   verifyFormat("export function A() {}\n"
878                "export default function B() {}\n"
879                "export function C() {}");
880   verifyFormat("export const x = 12;");
881   verifyFormat("export default class X {}");
882   verifyFormat("export {X, Y} from 'some/module.js';");
883   verifyFormat("export {\n"
884                "  X,\n"
885                "  Y,\n"
886                "} from 'some/module.js';");
887   verifyFormat("export class C {\n"
888                "  x: number;\n"
889                "  y: string;\n"
890                "}");
891   verifyFormat("export class X { y: number; }");
892   verifyFormat("export abstract class X { y: number; }");
893   verifyFormat("export default class X { y: number }");
894   verifyFormat("export default function() {\n  return 1;\n}");
895   verifyFormat("export var x = 12;");
896   verifyFormat("class C {}\n"
897                "export function f() {}\n"
898                "var v;");
899   verifyFormat("export var x: number = 12;");
900   verifyFormat("export const y = {\n"
901                "  a: 1,\n"
902                "  b: 2\n"
903                "};");
904   verifyFormat("export enum Foo {\n"
905                "  BAR,\n"
906                "  // adsdasd\n"
907                "  BAZ\n"
908                "}");
909   verifyFormat("export default [\n"
910                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
911                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
912                "];");
913   verifyFormat("export default [];");
914   verifyFormat("export default () => {};");
915   verifyFormat("export interface Foo { foo: number; }\n"
916                "export class Bar {\n"
917                "  blah(): string { return this.blah; };\n"
918                "}");
919 }
920 
921 TEST_F(FormatTestJS, TemplateStrings) {
922   // Keeps any whitespace/indentation within the template string.
923   EXPECT_EQ("var x = `hello\n"
924             "     ${  name    }\n"
925             "  !`;",
926             format("var x    =    `hello\n"
927                    "     ${  name    }\n"
928                    "  !`;"));
929 
930   verifyFormat("var x =\n"
931                "    `hello ${world}` >= some();",
932                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
933   verifyFormat("var x = `hello ${world}` >= some();",
934                getGoogleJSStyleWithColumns(35)); // Barely fits.
935   EXPECT_EQ("var x = `hello\n"
936             "  ${world}` >=\n"
937             "    some();",
938             format("var x =\n"
939                    "    `hello\n"
940                    "  ${world}` >= some();",
941                    getGoogleJSStyleWithColumns(21))); // Barely doesn't fit.
942   EXPECT_EQ("var x = `hello\n"
943             "  ${world}` >= some();",
944             format("var x =\n"
945                    "    `hello\n"
946                    "  ${world}` >= some();",
947                    getGoogleJSStyleWithColumns(22))); // Barely fits.
948 
949   verifyFormat("var x =\n"
950                "    `h`;",
951                getGoogleJSStyleWithColumns(11));
952   EXPECT_EQ(
953       "var x =\n    `multi\n  line`;",
954       format("var x = `multi\n  line`;", getGoogleJSStyleWithColumns(13)));
955   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
956                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
957 
958   // Make sure template strings get a proper ColumnWidth assigned, even if they
959   // are first token in line.
960   verifyFormat(
961       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
962       "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
963 
964   // Two template strings.
965   verifyFormat("var x = `hello` == `hello`;");
966 
967   // Comments in template strings.
968   EXPECT_EQ("var x = `//a`;\n"
969             "var y;",
970             format("var x =\n `//a`;\n"
971                    "var y  ;"));
972   EXPECT_EQ("var x = `/*a`;\n"
973             "var y;",
974             format("var x =\n `/*a`;\n"
975                    "var y;"));
976   // Unterminated string literals in a template string.
977   verifyFormat("var x = `'`;  // comment with matching quote '\n"
978                "var y;");
979   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
980                "var y;");
981   EXPECT_EQ("it(`'aaaaaaaaaaaaaaa   `, aaaaaaaaa);",
982             format("it(`'aaaaaaaaaaaaaaa   `,   aaaaaaaaa) ;",
983                    getGoogleJSStyleWithColumns(40)));
984   // Backticks in a comment - not a template string.
985   EXPECT_EQ("var x = 1  // `/*a`;\n"
986             "    ;",
987             format("var x =\n 1  // `/*a`;\n"
988                    "    ;"));
989   EXPECT_EQ("/* ` */ var x = 1; /* ` */",
990             format("/* ` */ var x\n= 1; /* ` */"));
991   // Comment spans multiple template strings.
992   EXPECT_EQ("var x = `/*a`;\n"
993             "var y = ` */ `;",
994             format("var x =\n `/*a`;\n"
995                    "var y =\n ` */ `;"));
996   // Escaped backtick.
997   EXPECT_EQ("var x = ` \\` a`;\n"
998             "var y;",
999             format("var x = ` \\` a`;\n"
1000                    "var y;"));
1001 }
1002 
1003 TEST_F(FormatTestJS, CastSyntax) { verifyFormat("var x = <type>foo;"); }
1004 
1005 TEST_F(FormatTestJS, TypeArguments) {
1006   verifyFormat("class X<Y> {}");
1007   verifyFormat("new X<Y>();");
1008   verifyFormat("foo<Y>(a);");
1009   verifyFormat("var x: X<Y>[];");
1010   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
1011   verifyFormat("function f(a: List<any> = null) {}");
1012   verifyFormat("function f(): List<any> {}");
1013   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
1014                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
1015   verifyFormat("function aaaaaaaaaa(\n"
1016                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
1017                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
1018                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
1019 }
1020 
1021 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
1022   verifyFormat(
1023       "function foo(check: Object):\n"
1024       "    check is {foo: string, bar: string, baz: string, foobar: string} {\n"
1025       "  return 'bar' in check;\n"
1026       "}\n");
1027 }
1028 
1029 TEST_F(FormatTestJS, OptionalTypes) {
1030   verifyFormat("function x(a?: b, c?, d?) {}");
1031   verifyFormat("class X {\n"
1032                "  y?: z;\n"
1033                "  z?;\n"
1034                "}");
1035   verifyFormat("interface X {\n"
1036                "  y?(): z;\n"
1037                "}");
1038   verifyFormat("x ? 1 : 2;");
1039   verifyFormat("constructor({aa}: {\n"
1040                "  aa?: string,\n"
1041                "  aaaaaaaa?: string,\n"
1042                "  aaaaaaaaaaaaaaa?: boolean,\n"
1043                "  aaaaaa?: List<string>\n"
1044                "}) {}");
1045 }
1046 
1047 TEST_F(FormatTestJS, IndexSignature) {
1048   verifyFormat("var x: {[k: string]: v};");
1049 }
1050 
1051 TEST_F(FormatTestJS, WrapAfterParen) {
1052   verifyFormat("xxxxxxxxxxx(\n"
1053                "    aaa, aaa);",
1054                getGoogleJSStyleWithColumns(20));
1055   verifyFormat("xxxxxxxxxxx(\n"
1056                "    aaa, aaa, aaa,\n"
1057                "    aaa, aaa, aaa);",
1058                getGoogleJSStyleWithColumns(20));
1059   verifyFormat("xxxxxxxxxxx(\n"
1060                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
1061                "    function(x) {\n"
1062                "      y();  //\n"
1063                "    });",
1064                getGoogleJSStyleWithColumns(40));
1065   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
1066                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
1067 }
1068 
1069 TEST_F(FormatTestJS, JSDocAnnotations) {
1070   EXPECT_EQ("/**\n"
1071             " * @export {this.is.a.long.path.to.a.Type}\n"
1072             " */",
1073             format("/**\n"
1074                    " * @export {this.is.a.long.path.to.a.Type}\n"
1075                    " */",
1076                    getGoogleJSStyleWithColumns(20)));
1077 }
1078 
1079 } // end namespace tooling
1080 } // end namespace clang
1081