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