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