xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision 09840efd92cca6713fd0e71543b21d201da636d6)
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, AutomaticSemicolonInsertion) {
549   // The following statements must not wrap, as otherwise the program meaning
550   // would change due to automatic semicolon insertion.
551   // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
552   verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10));
553   verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10));
554   verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10));
555   verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
556   verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
557   verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
558 }
559 
560 TEST_F(FormatTestJS, ClosureStyleCasts) {
561   verifyFormat("var x = /** @type {foo} */ (bar);");
562 }
563 
564 TEST_F(FormatTestJS, TryCatch) {
565   verifyFormat("try {\n"
566                "  f();\n"
567                "} catch (e) {\n"
568                "  g();\n"
569                "} finally {\n"
570                "  h();\n"
571                "}");
572 
573   // But, of course, "catch" is a perfectly fine function name in JavaScript.
574   verifyFormat("someObject.catch();");
575   verifyFormat("someObject.new();");
576   verifyFormat("someObject.delete();");
577 }
578 
579 TEST_F(FormatTestJS, StringLiteralConcatenation) {
580   verifyFormat("var literal = 'hello ' +\n"
581                "              'world';");
582 }
583 
584 TEST_F(FormatTestJS, RegexLiteralClassification) {
585   // Regex literals.
586   verifyFormat("var regex = /abc/;");
587   verifyFormat("f(/abc/);");
588   verifyFormat("f(abc, /abc/);");
589   verifyFormat("some_map[/abc/];");
590   verifyFormat("var x = a ? /abc/ : /abc/;");
591   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
592   verifyFormat("var x = !/abc/.test(y);");
593   verifyFormat("var x = a && /abc/.test(y);");
594   verifyFormat("var x = a || /abc/.test(y);");
595   verifyFormat("var x = a + /abc/.search(y);");
596   verifyFormat("/abc/.search(y);");
597   verifyFormat("var regexs = {/abc/, /abc/};");
598   verifyFormat("return /abc/;");
599 
600   // Not regex literals.
601   verifyFormat("var a = a / 2 + b / 3;");
602   verifyFormat("var a = a++ / 2;");
603   // Prefix unary can operate on regex literals, not that it makes sense.
604   verifyFormat("var a = ++/a/;");
605 
606   // This is a known issue, regular expressions are incorrectly detected if
607   // directly following a closing parenthesis.
608   verifyFormat("if (foo) / bar /.exec(baz);");
609 }
610 
611 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
612   verifyFormat("var regex = /=/;");
613   verifyFormat("var regex = /a*/;");
614   verifyFormat("var regex = /a+/;");
615   verifyFormat("var regex = /a?/;");
616   verifyFormat("var regex = /.a./;");
617   verifyFormat("var regex = /a\\*/;");
618   verifyFormat("var regex = /^a$/;");
619   verifyFormat("var regex = /\\/a/;");
620   verifyFormat("var regex = /(?:x)/;");
621   verifyFormat("var regex = /x(?=y)/;");
622   verifyFormat("var regex = /x(?!y)/;");
623   verifyFormat("var regex = /x|y/;");
624   verifyFormat("var regex = /a{2}/;");
625   verifyFormat("var regex = /a{1,3}/;");
626 
627   verifyFormat("var regex = /[abc]/;");
628   verifyFormat("var regex = /[^abc]/;");
629   verifyFormat("var regex = /[\\b]/;");
630   verifyFormat("var regex = /[/]/;");
631   verifyFormat("var regex = /[\\/]/;");
632   verifyFormat("var regex = /\\[/;");
633   verifyFormat("var regex = /\\\\[/]/;");
634   verifyFormat("var regex = /}[\"]/;");
635   verifyFormat("var regex = /}[/\"]/;");
636   verifyFormat("var regex = /}[\"/]/;");
637 
638   verifyFormat("var regex = /\\b/;");
639   verifyFormat("var regex = /\\B/;");
640   verifyFormat("var regex = /\\d/;");
641   verifyFormat("var regex = /\\D/;");
642   verifyFormat("var regex = /\\f/;");
643   verifyFormat("var regex = /\\n/;");
644   verifyFormat("var regex = /\\r/;");
645   verifyFormat("var regex = /\\s/;");
646   verifyFormat("var regex = /\\S/;");
647   verifyFormat("var regex = /\\t/;");
648   verifyFormat("var regex = /\\v/;");
649   verifyFormat("var regex = /\\w/;");
650   verifyFormat("var regex = /\\W/;");
651   verifyFormat("var regex = /a(a)\\1/;");
652   verifyFormat("var regex = /\\0/;");
653   verifyFormat("var regex = /\\\\/g;");
654   verifyFormat("var regex = /\\a\\\\/g;");
655   verifyFormat("var regex = /\a\\//g;");
656   verifyFormat("var regex = /a\\//;\n"
657                "var x = 0;");
658   EXPECT_EQ("var regex = /'/g;", format("var regex = /'/g ;"));
659   EXPECT_EQ("var regex = /'/g;  //'", format("var regex = /'/g ; //'"));
660   EXPECT_EQ("var regex = /\\/*/;\n"
661             "var x = 0;",
662             format("var regex = /\\/*/;\n"
663                    "var x=0;"));
664   EXPECT_EQ("var x = /a\\//;", format("var x = /a\\//  \n;"));
665   verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
666   verifyFormat("var regex =\n"
667                "    /\"/;",
668                getGoogleJSStyleWithColumns(15));
669   verifyFormat("var regex =  //\n"
670                "    /a/;");
671   verifyFormat("var regexs = [\n"
672                "  /d/,   //\n"
673                "  /aa/,  //\n"
674                "];");
675 }
676 
677 TEST_F(FormatTestJS, RegexLiteralModifiers) {
678   verifyFormat("var regex = /abc/g;");
679   verifyFormat("var regex = /abc/i;");
680   verifyFormat("var regex = /abc/m;");
681   verifyFormat("var regex = /abc/y;");
682 }
683 
684 TEST_F(FormatTestJS, RegexLiteralLength) {
685   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
686                getGoogleJSStyleWithColumns(60));
687   verifyFormat("var regex =\n"
688                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
689                getGoogleJSStyleWithColumns(60));
690   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
691                getGoogleJSStyleWithColumns(50));
692 }
693 
694 TEST_F(FormatTestJS, RegexLiteralExamples) {
695   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
696 }
697 
698 TEST_F(FormatTestJS, TypeAnnotations) {
699   verifyFormat("var x: string;");
700   verifyFormat("function x(): string {\n  return 'x';\n}");
701   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
702   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
703   verifyFormat("for (var y: string in x) {\n  x();\n}");
704   verifyFormat("((a: string, b: number): string => a + b);");
705   verifyFormat("var x: (y: number) => string;");
706   verifyFormat("var x: P<string, (a: number) => string>;");
707   verifyFormat("var x = {y: function(): z { return 1; }};");
708   verifyFormat("var x = {y: function(): {a: number} { return 1; }};");
709 }
710 
711 TEST_F(FormatTestJS, ClassDeclarations) {
712   verifyFormat("class C {\n  x: string = 12;\n}");
713   verifyFormat("class C {\n  x(): string => 12;\n}");
714   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
715   verifyFormat("class C {\n  private x: string = 12;\n}");
716   verifyFormat("class C {\n  private static x: string = 12;\n}");
717   verifyFormat("class C {\n  static x(): string { return 'asd'; }\n}");
718   verifyFormat("class C extends P implements I {}");
719   verifyFormat("class C extends p.P implements i.I {}");
720   verifyFormat("class Test {\n"
721                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
722                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
723                "}");
724 
725   // ':' is not a type declaration here.
726   verifyFormat("class X {\n"
727                "  subs = {\n"
728                "    'b': {\n"
729                "      'c': 1,\n"
730                "    },\n"
731                "  };\n"
732                "}");
733 }
734 
735 TEST_F(FormatTestJS, InterfaceDeclarations) {
736   verifyFormat("interface I {\n"
737                "  x: string;\n"
738                "}\n"
739                "var y;");
740   // Ensure that state is reset after parsing the interface.
741   verifyFormat("interface a {}\n"
742                "export function b() {}\n"
743                "var x;");
744 }
745 
746 TEST_F(FormatTestJS, EnumDeclarations) {
747   verifyFormat("enum Foo {\n"
748                "  A = 1,\n"
749                "  B\n"
750                "}");
751   verifyFormat("export /* somecomment*/ enum Foo {\n"
752                "  A = 1,\n"
753                "  B\n"
754                "}");
755   verifyFormat("enum Foo {\n"
756                "  A = 1,  // comment\n"
757                "  B\n"
758                "}\n"
759                "var x = 1;");
760 }
761 
762 TEST_F(FormatTestJS, MetadataAnnotations) {
763   verifyFormat("@A\nclass C {\n}");
764   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
765   verifyFormat("@A\n@B\nclass C {\n}");
766   verifyFormat("class C {\n  @A x: string;\n}");
767   verifyFormat("class C {\n"
768                "  @A\n"
769                "  private x(): string {\n"
770                "    return 'y';\n"
771                "  }\n"
772                "}");
773   verifyFormat("class X {}\n"
774                "class Y {}");
775 }
776 
777 TEST_F(FormatTestJS, Modules) {
778   verifyFormat("import SomeThing from 'some/module.js';");
779   verifyFormat("import {X, Y} from 'some/module.js';");
780   verifyFormat("import {\n"
781                "  VeryLongImportsAreAnnoying,\n"
782                "  VeryLongImportsAreAnnoying,\n"
783                "  VeryLongImportsAreAnnoying,\n"
784                "  VeryLongImportsAreAnnoying\n"
785                "} from 'some/module.js';");
786   verifyFormat("import {\n"
787                "  X,\n"
788                "  Y,\n"
789                "} from 'some/module.js';");
790   verifyFormat("import {\n"
791                "  X,\n"
792                "  Y,\n"
793                "} from 'some/long/module.js';",
794                getGoogleJSStyleWithColumns(20));
795   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
796   verifyFormat("import * as lib from 'some/module.js';");
797   verifyFormat("var x = {import: 1};\nx.import = 2;");
798 
799   verifyFormat("export function fn() {\n"
800                "  return 'fn';\n"
801                "}");
802   verifyFormat("export function A() {}\n"
803                "export default function B() {}\n"
804                "export function C() {}");
805   verifyFormat("export const x = 12;");
806   verifyFormat("export default class X {}");
807   verifyFormat("export {X, Y} from 'some/module.js';");
808   verifyFormat("export {\n"
809                "  X,\n"
810                "  Y,\n"
811                "} from 'some/module.js';");
812   verifyFormat("export class C {\n"
813                "  x: number;\n"
814                "  y: string;\n"
815                "}");
816   verifyFormat("export class X { y: number; }");
817   verifyFormat("export default class X { y: number }");
818   verifyFormat("export default function() {\n  return 1;\n}");
819   verifyFormat("export var x = 12;");
820   verifyFormat("class C {}\n"
821                "export function f() {}\n"
822                "var v;");
823   verifyFormat("export var x: number = 12;");
824   verifyFormat("export const y = {\n"
825                "  a: 1,\n"
826                "  b: 2\n"
827                "};");
828   verifyFormat("export enum Foo {\n"
829                "  BAR,\n"
830                "  // adsdasd\n"
831                "  BAZ\n"
832                "}");
833 }
834 
835 TEST_F(FormatTestJS, TemplateStrings) {
836   // Keeps any whitespace/indentation within the template string.
837   EXPECT_EQ("var x = `hello\n"
838             "     ${  name    }\n"
839             "  !`;",
840             format("var x    =    `hello\n"
841                    "     ${  name    }\n"
842                    "  !`;"));
843 
844   verifyFormat("var x =\n"
845                "    `hello ${world}` >= some();",
846                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
847   verifyFormat("var x = `hello ${world}` >= some();",
848                getGoogleJSStyleWithColumns(35)); // Barely fits.
849   EXPECT_EQ("var x = `hello\n"
850             "  ${world}` >=\n"
851             "        some();",
852             format("var x =\n"
853                    "    `hello\n"
854                    "  ${world}` >= some();",
855                    getGoogleJSStyleWithColumns(21))); // Barely doesn't fit.
856   EXPECT_EQ("var x = `hello\n"
857             "  ${world}` >= some();",
858             format("var x =\n"
859                    "    `hello\n"
860                    "  ${world}` >= some();",
861                    getGoogleJSStyleWithColumns(22))); // Barely fits.
862 
863   verifyFormat("var x =\n"
864                "    `h`;",
865                getGoogleJSStyleWithColumns(11));
866   EXPECT_EQ(
867       "var x =\n    `multi\n  line`;",
868       format("var x = `multi\n  line`;", getGoogleJSStyleWithColumns(13)));
869   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
870                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
871 
872   // Make sure template strings get a proper ColumnWidth assigned, even if they
873   // are first token in line.
874   verifyFormat(
875       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
876       "        `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
877 
878   // Two template strings.
879   verifyFormat("var x = `hello` == `hello`;");
880 
881   // Comments in template strings.
882   EXPECT_EQ("var x = `//a`;\n"
883             "var y;",
884             format("var x =\n `//a`;\n"
885                    "var y  ;"));
886   EXPECT_EQ("var x = `/*a`;\n"
887             "var y;",
888             format("var x =\n `/*a`;\n"
889                    "var y;"));
890   // Unterminated string literals in a template string.
891   verifyFormat("var x = `'`;  // comment with matching quote '\n"
892                "var y;");
893   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
894                "var y;");
895   // Backticks in a comment - not a template string.
896   EXPECT_EQ("var x = 1  // `/*a`;\n"
897             "    ;",
898             format("var x =\n 1  // `/*a`;\n"
899                    "    ;"));
900   EXPECT_EQ("/* ` */ var x = 1; /* ` */",
901             format("/* ` */ var x\n= 1; /* ` */"));
902   // Comment spans multiple template strings.
903   EXPECT_EQ("var x = `/*a`;\n"
904             "var y = ` */ `;",
905             format("var x =\n `/*a`;\n"
906                    "var y =\n ` */ `;"));
907   // Escaped backtick.
908   EXPECT_EQ("var x = ` \\` a`;\n"
909             "var y;",
910             format("var x = ` \\` a`;\n"
911                    "var y;"));
912 }
913 
914 TEST_F(FormatTestJS, CastSyntax) { verifyFormat("var x = <type>foo;"); }
915 
916 TEST_F(FormatTestJS, TypeArguments) {
917   verifyFormat("class X<Y> {}");
918   verifyFormat("new X<Y>();");
919   verifyFormat("foo<Y>(a);");
920   verifyFormat("var x: X<Y>[];");
921   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
922   verifyFormat("function f(a: List<any> = null) {}");
923   verifyFormat("function f(): List<any> {}");
924   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
925                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
926   verifyFormat("function aaaaaaaaaa(\n"
927                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
928                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
929                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
930 }
931 
932 TEST_F(FormatTestJS, OptionalTypes) {
933   verifyFormat("function x(a?: b, c?, d?) {}");
934   verifyFormat("class X {\n"
935                "  y?: z;\n"
936                "  z?;\n"
937                "}");
938   verifyFormat("interface X {\n"
939                "  y?(): z;\n"
940                "}");
941   verifyFormat("x ? 1 : 2;");
942   verifyFormat("constructor({aa}: {\n"
943                "  aa?: string,\n"
944                "  aaaaaaaa?: string,\n"
945                "  aaaaaaaaaaaaaaa?: boolean,\n"
946                "  aaaaaa?: List<string>\n"
947                "}) {}");
948 }
949 
950 TEST_F(FormatTestJS, IndexSignature) {
951   verifyFormat("var x: {[k: string]: v};");
952 }
953 
954 TEST_F(FormatTestJS, WrapAfterParen) {
955   verifyFormat("xxxxxxxxxxx(\n"
956                "    aaa, aaa);",
957                getGoogleJSStyleWithColumns(20));
958   verifyFormat("xxxxxxxxxxx(\n"
959                "    aaa, aaa, aaa,\n"
960                "    aaa, aaa, aaa);",
961                getGoogleJSStyleWithColumns(20));
962   verifyFormat("xxxxxxxxxxx(\n"
963                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
964                "    function(x) {\n"
965                "      y();  //\n"
966                "    });",
967                getGoogleJSStyleWithColumns(40));
968   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
969                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
970 }
971 
972 } // end namespace tooling
973 } // end namespace clang
974