xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision e6fcf7d372ca822b06112d92856895c2fce38878)
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("var aaaaa: List<SomeThing> =\n"
260                "    [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];");
261   verifyFormat("return [\n"
262                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
263                "  bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
264                "  ccccccccccccccccccccccccccc\n"
265                "];");
266   verifyFormat("var someVariable = SomeFuntion([\n"
267                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
268                "  bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
269                "  ccccccccccccccccccccccccccc\n"
270                "]);");
271   verifyFormat("var someVariable = SomeFuntion([\n"
272                "  [aaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbb],\n"
273                "]);",
274                getGoogleJSStyleWithColumns(51));
275   verifyFormat("var someVariable = SomeFuntion(aaaa, [\n"
276                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
277                "  bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
278                "  ccccccccccccccccccccccccccc\n"
279                "]);");
280   verifyFormat("var someVariable = SomeFuntion(aaaa,\n"
281                "                               [\n"
282                "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
283                "                                 bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
284                "                                 ccccccccccccccccccccccccccc\n"
285                "                               ],\n"
286                "                               aaaa);");
287 
288   verifyFormat("someFunction([], {a: a});");
289 }
290 
291 TEST_F(FormatTestJS, FunctionLiterals) {
292   verifyFormat("doFoo(function() {});");
293   verifyFormat("doFoo(function() { return 1; });");
294   verifyFormat("var func = function() {\n"
295                "  return 1;\n"
296                "};");
297   verifyFormat("return {\n"
298                "  body: {\n"
299                "    setAttribute: function(key, val) { this[key] = val; },\n"
300                "    getAttribute: function(key) { return this[key]; },\n"
301                "    style: {direction: ''}\n"
302                "  }\n"
303                "};");
304   EXPECT_EQ("abc = xyz ?\n"
305             "          function() {\n"
306             "            return 1;\n"
307             "          } :\n"
308             "          function() {\n"
309             "            return -1;\n"
310             "          };",
311             format("abc=xyz?function(){return 1;}:function(){return -1;};"));
312 
313   verifyFormat("var closure = goog.bind(\n"
314                "    function() {  // comment\n"
315                "      foo();\n"
316                "      bar();\n"
317                "    },\n"
318                "    this, arg1IsReallyLongAndNeeedsLineBreaks,\n"
319                "    arg3IsReallyLongAndNeeedsLineBreaks);");
320   verifyFormat("var closure = goog.bind(function() {  // comment\n"
321                "  foo();\n"
322                "  bar();\n"
323                "}, this);");
324   verifyFormat("return {\n"
325                "  a: 'E',\n"
326                "  b: function() {\n"
327                "    return function() {\n"
328                "      f();  //\n"
329                "    };\n"
330                "  }\n"
331                "};");
332   verifyFormat("{\n"
333                "  var someVariable = function(x) {\n"
334                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
335                "  };\n"
336                "}");
337   verifyFormat("someLooooooooongFunction(\n"
338                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
339                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
340                "    function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
341                "      // code\n"
342                "    });");
343 
344   verifyFormat("f({a: function() { return 1; }});",
345                getGoogleJSStyleWithColumns(33));
346   verifyFormat("f({\n"
347                "  a: function() { return 1; }\n"
348                "});",
349                getGoogleJSStyleWithColumns(32));
350 
351   verifyFormat("return {\n"
352                "  a: function SomeFunction() {\n"
353                "    // ...\n"
354                "    return 1;\n"
355                "  }\n"
356                "};");
357   verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
358                "    .then(goog.bind(function(aaaaaaaaaaa) {\n"
359                "      someFunction();\n"
360                "      someFunction();\n"
361                "    }, this), aaaaaaaaaaaaaaaaa);");
362 
363   // FIXME: This is not ideal yet.
364   verifyFormat("someFunction(goog.bind(\n"
365                "                 function() {\n"
366                "                   doSomething();\n"
367                "                   doSomething();\n"
368                "                 },\n"
369                "                 this),\n"
370                "             goog.bind(function() {\n"
371                "               doSomething();\n"
372                "               doSomething();\n"
373                "             }, this));");
374 
375   // FIXME: This is bad, we should be wrapping before "function() {".
376   verifyFormat("someFunction(function() {\n"
377                "  doSomething();  // break\n"
378                "})\n"
379                "    .doSomethingElse(\n"
380                "        // break\n"
381                "        );");
382 }
383 
384 TEST_F(FormatTestJS, InliningFunctionLiterals) {
385   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
386   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
387   verifyFormat("var func = function() {\n"
388                "  return 1;\n"
389                "};",
390                Style);
391   verifyFormat("var func = doSomething(function() { return 1; });", Style);
392   verifyFormat("var outer = function() {\n"
393                "  var inner = function() { return 1; }\n"
394                "};",
395                Style);
396   verifyFormat("function outer1(a, b) {\n"
397                "  function inner1(a, b) { return a; }\n"
398                "}",
399                Style);
400 
401   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
402   verifyFormat("var func = function() { return 1; };", Style);
403   verifyFormat("var func = doSomething(function() { return 1; });", Style);
404   verifyFormat(
405       "var outer = function() { var inner = function() { return 1; } };",
406       Style);
407   verifyFormat("function outer1(a, b) {\n"
408                "  function inner1(a, b) { return a; }\n"
409                "}",
410                Style);
411 
412   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
413   verifyFormat("var func = function() {\n"
414                "  return 1;\n"
415                "};",
416                Style);
417   verifyFormat("var func = doSomething(function() {\n"
418                "  return 1;\n"
419                "});",
420                Style);
421   verifyFormat("var outer = function() {\n"
422                "  var inner = function() {\n"
423                "    return 1;\n"
424                "  }\n"
425                "};",
426                Style);
427   verifyFormat("function outer1(a, b) {\n"
428                "  function inner1(a, b) {\n"
429                "    return a;\n"
430                "  }\n"
431                "}",
432                Style);
433 }
434 
435 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
436   verifyFormat("promise.then(\n"
437                "    function success() {\n"
438                "      doFoo();\n"
439                "      doBar();\n"
440                "    },\n"
441                "    function error() {\n"
442                "      doFoo();\n"
443                "      doBaz();\n"
444                "    },\n"
445                "    []);\n");
446   verifyFormat("promise.then(\n"
447                "    function success() {\n"
448                "      doFoo();\n"
449                "      doBar();\n"
450                "    },\n"
451                "    [],\n"
452                "    function error() {\n"
453                "      doFoo();\n"
454                "      doBaz();\n"
455                "    });\n");
456   // FIXME: Here, we should probably break right after the "(" for consistency.
457   verifyFormat("promise.then([],\n"
458                "             function success() {\n"
459                "               doFoo();\n"
460                "               doBar();\n"
461                "             },\n"
462                "             function error() {\n"
463                "               doFoo();\n"
464                "               doBaz();\n"
465                "             });\n");
466 
467   verifyFormat("getSomeLongPromise()\n"
468                "    .then(function(value) { body(); })\n"
469                "    .thenCatch(function(error) {\n"
470                "      body();\n"
471                "      body();\n"
472                "    });");
473   verifyFormat("getSomeLongPromise()\n"
474                "    .then(function(value) {\n"
475                "      body();\n"
476                "      body();\n"
477                "    })\n"
478                "    .thenCatch(function(error) {\n"
479                "      body();\n"
480                "      body();\n"
481                "    });");
482 
483   verifyFormat("getSomeLongPromise()\n"
484                "    .then(function(value) { body(); })\n"
485                "    .thenCatch(function(error) { body(); });");
486 }
487 
488 TEST_F(FormatTestJS, ArrowFunctions) {
489   verifyFormat("var x = (a) => {\n"
490                "  return a;\n"
491                "};");
492   verifyFormat("var x = (a) => {\n"
493                "  function y() { return 42; }\n"
494                "  return a;\n"
495                "};");
496   verifyFormat("var x = (a: type): {some: type} => {\n"
497                "  return a;\n"
498                "};");
499   verifyFormat("var x = (a) => a;");
500   verifyFormat("return () => [];");
501   verifyFormat("var aaaaaaaaaaaaaaaaaaaa = {\n"
502                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
503                "      (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
504                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) =>\n"
505                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
506                "};");
507   verifyFormat(
508       "var a = a.aaaaaaa((a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) &&\n"
509       "                            aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
510   verifyFormat(
511       "var a = a.aaaaaaa((a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) ?\n"
512       "                                aaaaaaaaaaaaaaaaaaaaa(bbbbbbb) :\n"
513       "                                aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
514 
515   // FIXME: This is bad, we should be wrapping before "() => {".
516   verifyFormat("someFunction(() => {\n"
517                "  doSomething();  // break\n"
518                "})\n"
519                "    .doSomethingElse(\n"
520                "        // break\n"
521                "        );");
522 }
523 
524 TEST_F(FormatTestJS, ReturnStatements) {
525   verifyFormat("function() {\n"
526                "  return [hello, world];\n"
527                "}");
528 }
529 
530 TEST_F(FormatTestJS, AutomaticSemicolonInsertion) {
531   // The following statements must not wrap, as otherwise the program meaning
532   // would change due to automatic semicolon insertion.
533   // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
534   verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10));
535   verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10));
536   verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10));
537   verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
538   verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
539   verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
540 }
541 
542 TEST_F(FormatTestJS, ClosureStyleCasts) {
543   verifyFormat("var x = /** @type {foo} */ (bar);");
544 }
545 
546 TEST_F(FormatTestJS, TryCatch) {
547   verifyFormat("try {\n"
548                "  f();\n"
549                "} catch (e) {\n"
550                "  g();\n"
551                "} finally {\n"
552                "  h();\n"
553                "}");
554 
555   // But, of course, "catch" is a perfectly fine function name in JavaScript.
556   verifyFormat("someObject.catch();");
557   verifyFormat("someObject.new();");
558   verifyFormat("someObject.delete();");
559 }
560 
561 TEST_F(FormatTestJS, StringLiteralConcatenation) {
562   verifyFormat("var literal = 'hello ' +\n"
563                "              'world';");
564 }
565 
566 TEST_F(FormatTestJS, RegexLiteralClassification) {
567   // Regex literals.
568   verifyFormat("var regex = /abc/;");
569   verifyFormat("f(/abc/);");
570   verifyFormat("f(abc, /abc/);");
571   verifyFormat("some_map[/abc/];");
572   verifyFormat("var x = a ? /abc/ : /abc/;");
573   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
574   verifyFormat("var x = !/abc/.test(y);");
575   verifyFormat("var x = a && /abc/.test(y);");
576   verifyFormat("var x = a || /abc/.test(y);");
577   verifyFormat("var x = a + /abc/.search(y);");
578   verifyFormat("var regexs = {/abc/, /abc/};");
579   verifyFormat("return /abc/;");
580 
581   // Not regex literals.
582   verifyFormat("var a = a / 2 + b / 3;");
583 }
584 
585 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
586   verifyFormat("var regex = /=/;");
587   verifyFormat("var regex = /a*/;");
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 = /(?:x)/;");
595   verifyFormat("var regex = /x(?=y)/;");
596   verifyFormat("var regex = /x(?!y)/;");
597   verifyFormat("var regex = /x|y/;");
598   verifyFormat("var regex = /a{2}/;");
599   verifyFormat("var regex = /a{1,3}/;");
600   verifyFormat("var regex = /[abc]/;");
601   verifyFormat("var regex = /[^abc]/;");
602   verifyFormat("var regex = /[\\b]/;");
603   verifyFormat("var regex = /\\b/;");
604   verifyFormat("var regex = /\\B/;");
605   verifyFormat("var regex = /\\d/;");
606   verifyFormat("var regex = /\\D/;");
607   verifyFormat("var regex = /\\f/;");
608   verifyFormat("var regex = /\\n/;");
609   verifyFormat("var regex = /\\r/;");
610   verifyFormat("var regex = /\\s/;");
611   verifyFormat("var regex = /\\S/;");
612   verifyFormat("var regex = /\\t/;");
613   verifyFormat("var regex = /\\v/;");
614   verifyFormat("var regex = /\\w/;");
615   verifyFormat("var regex = /\\W/;");
616   verifyFormat("var regex = /a(a)\\1/;");
617   verifyFormat("var regex = /\\0/;");
618   verifyFormat("var regex = /\\\\/g;");
619   verifyFormat("var regex = /\\a\\\\/g;");
620   verifyFormat("var regex = /\a\\//g;");
621   verifyFormat("var regex = /a\\//;\n"
622                "var x = 0;");
623   EXPECT_EQ("var regex = /\\/*/;\n"
624             "var x = 0;",
625             format("var regex = /\\/*/;\n"
626                    "var x=0;"));
627 }
628 
629 TEST_F(FormatTestJS, RegexLiteralModifiers) {
630   verifyFormat("var regex = /abc/g;");
631   verifyFormat("var regex = /abc/i;");
632   verifyFormat("var regex = /abc/m;");
633   verifyFormat("var regex = /abc/y;");
634 }
635 
636 TEST_F(FormatTestJS, RegexLiteralLength) {
637   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
638                getGoogleJSStyleWithColumns(60));
639   verifyFormat("var regex =\n"
640                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
641                getGoogleJSStyleWithColumns(60));
642   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
643                getGoogleJSStyleWithColumns(50));
644 }
645 
646 TEST_F(FormatTestJS, RegexLiteralExamples) {
647   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
648 }
649 
650 TEST_F(FormatTestJS, TypeAnnotations) {
651   verifyFormat("var x: string;");
652   verifyFormat("function x(): string {\n  return 'x';\n}");
653   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
654   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
655   verifyFormat("for (var y: string in x) {\n  x();\n}");
656   verifyFormat("((a: string, b: number): string => a + b);");
657   verifyFormat("var x: (y: number) => string;");
658   verifyFormat("var x: P<string, (a: number) => string>;");
659   verifyFormat("var x = {y: function(): z { return 1; }};");
660   verifyFormat("var x = {y: function(): {a: number} { return 1; }};");
661 }
662 
663 TEST_F(FormatTestJS, ClassDeclarations) {
664   verifyFormat("class C {\n  x: string = 12;\n}");
665   verifyFormat("class C {\n  x(): string => 12;\n}");
666   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
667   verifyFormat("class C {\n  private x: string = 12;\n}");
668   verifyFormat("class C {\n  private static x: string = 12;\n}");
669   verifyFormat("class C {\n  static x(): string { return 'asd'; }\n}");
670   verifyFormat("class C extends P implements I {}");
671   verifyFormat("class C extends p.P implements i.I {}");
672 
673   // ':' is not a type declaration here.
674   verifyFormat("class X {\n"
675                "  subs = {\n"
676                "    'b': {\n"
677                "      'c': 1,\n"
678                "    },\n"
679                "  };\n"
680                "}");
681 }
682 
683 TEST_F(FormatTestJS, InterfaceDeclarations) {
684   verifyFormat("interface I {\n"
685                "  x: string;\n"
686                "}\n"
687                "var y;");
688 }
689 
690 TEST_F(FormatTestJS, EnumDeclarations) {
691   verifyFormat("enum Foo {\n"
692                "  A = 1,\n"
693                "  B\n"
694                "}");
695   verifyFormat("export /* somecomment*/ enum Foo {\n"
696                "  A = 1,\n"
697                "  B\n"
698                "}");
699   verifyFormat("enum Foo {\n"
700                "  A = 1,  // comment\n"
701                "  B\n"
702                "}\n"
703                "var x = 1;");
704 }
705 
706 TEST_F(FormatTestJS, MetadataAnnotations) {
707   verifyFormat("@A\nclass C {\n}");
708   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
709   verifyFormat("@A\n@B\nclass C {\n}");
710   verifyFormat("class C {\n  @A x: string;\n}");
711   verifyFormat("class C {\n"
712                "  @A\n"
713                "  private x(): string {\n"
714                "    return 'y';\n"
715                "  }\n"
716                "}");
717   verifyFormat("class X {}\n"
718                "class Y {}");
719 }
720 
721 TEST_F(FormatTestJS, Modules) {
722   verifyFormat("import SomeThing from 'some/module.js';");
723   verifyFormat("import {X, Y} from 'some/module.js';");
724   verifyFormat("import {\n"
725                "  VeryLongImportsAreAnnoying,\n"
726                "  VeryLongImportsAreAnnoying,\n"
727                "  VeryLongImportsAreAnnoying,\n"
728                "  VeryLongImportsAreAnnoying\n"
729                "} from 'some/module.js';");
730   verifyFormat("import {\n"
731                "  X,\n"
732                "  Y,\n"
733                "} from 'some/module.js';");
734   verifyFormat("import {\n"
735                "  X,\n"
736                "  Y,\n"
737                "} from 'some/long/module.js';",
738                getGoogleJSStyleWithColumns(20));
739   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
740   verifyFormat("import * as lib from 'some/module.js';");
741   verifyFormat("var x = {import: 1};\nx.import = 2;");
742 
743   verifyFormat("export function fn() {\n"
744                "  return 'fn';\n"
745                "}");
746   verifyFormat("export function A() {}\n"
747                "export default function B() {}\n"
748                "export function C() {}");
749   verifyFormat("export const x = 12;");
750   verifyFormat("export default class X {}");
751   verifyFormat("export {X, Y} from 'some/module.js';");
752   verifyFormat("export {\n"
753                "  X,\n"
754                "  Y,\n"
755                "} from 'some/module.js';");
756   verifyFormat("export class C {\n"
757                "  x: number;\n"
758                "  y: string;\n"
759                "}");
760   verifyFormat("export class X { y: number; }");
761   verifyFormat("export default class X { y: number }");
762   verifyFormat("export default function() {\n  return 1;\n}");
763   verifyFormat("export var x = 12;");
764   verifyFormat("class C {}\n"
765                "export function f() {}\n"
766                "var v;");
767   verifyFormat("export var x: number = 12;");
768   verifyFormat("export const y = {\n"
769                "  a: 1,\n"
770                "  b: 2\n"
771                "};");
772   verifyFormat("export enum Foo {\n"
773                "  BAR,\n"
774                "  // adsdasd\n"
775                "  BAZ\n"
776                "}");
777 }
778 
779 TEST_F(FormatTestJS, TemplateStrings) {
780   // Keeps any whitespace/indentation within the template string.
781   EXPECT_EQ("var x = `hello\n"
782             "     ${  name    }\n"
783             "  !`;",
784             format("var x    =    `hello\n"
785                    "     ${  name    }\n"
786                    "  !`;"));
787 
788   // FIXME: +1 / -1 offsets are to work around clang-format miscalculating
789   // widths for unknown tokens that are not whitespace (e.g. '`'). Remove when
790   // the code is corrected.
791 
792   verifyFormat("var x =\n"
793                "    `hello ${world}` >= some();",
794                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
795   verifyFormat("var x = `hello ${world}` >= some();",
796                getGoogleJSStyleWithColumns(35 + 1)); // Barely fits.
797   EXPECT_EQ("var x = `hello\n"
798             "  ${world}` >=\n"
799             "        some();",
800             format("var x =\n"
801                    "    `hello\n"
802                    "  ${world}` >= some();",
803                    getGoogleJSStyleWithColumns(21))); // Barely doesn't fit.
804   EXPECT_EQ("var x = `hello\n"
805             "  ${world}` >= some();",
806             format("var x =\n"
807                    "    `hello\n"
808                    "  ${world}` >= some();",
809                    getGoogleJSStyleWithColumns(22))); // Barely fits.
810 
811   verifyFormat("var x =\n    `h`;", getGoogleJSStyleWithColumns(13 - 1));
812   EXPECT_EQ(
813       "var x =\n    `multi\n  line`;",
814       format("var x = `multi\n  line`;", getGoogleJSStyleWithColumns(14 - 1)));
815 
816   // Make sure template strings get a proper ColumnWidth assigned, even if they
817   // are first token in line.
818   verifyFormat(
819       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
820       "        `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
821 
822   // Two template strings.
823   verifyFormat("var x = `hello` == `hello`;");
824 
825   // Comments in template strings.
826   EXPECT_EQ("var x = `//a`;\n"
827             "var y;",
828             format("var x =\n `//a`;\n"
829                    "var y  ;"));
830   EXPECT_EQ("var x = `/*a`;\n"
831             "var y;",
832             format("var x =\n `/*a`;\n"
833                    "var y;"));
834   // Unterminated string literals in a template string.
835   verifyFormat("var x = `'`;  // comment with matching quote '\n"
836                "var y;");
837   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
838                "var y;");
839   // Backticks in a comment - not a template string.
840   EXPECT_EQ("var x = 1  // `/*a`;\n"
841             "    ;",
842             format("var x =\n 1  // `/*a`;\n"
843                    "    ;"));
844   EXPECT_EQ("/* ` */ var x = 1; /* ` */",
845             format("/* ` */ var x\n= 1; /* ` */"));
846   // Comment spans multiple template strings.
847   EXPECT_EQ("var x = `/*a`;\n"
848             "var y = ` */ `;",
849             format("var x =\n `/*a`;\n"
850                    "var y =\n ` */ `;"));
851   // Escaped backtick.
852   EXPECT_EQ("var x = ` \\` a`;\n"
853             "var y;",
854             format("var x = ` \\` a`;\n"
855                    "var y;"));
856 }
857 
858 TEST_F(FormatTestJS, CastSyntax) { verifyFormat("var x = <type>foo;"); }
859 
860 TEST_F(FormatTestJS, TypeArguments) {
861   verifyFormat("class X<Y> {}");
862   verifyFormat("new X<Y>();");
863   verifyFormat("foo<Y>(a);");
864   verifyFormat("var x: X<Y>[];");
865   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
866   verifyFormat("function f(a: List<any> = null) {}");
867   verifyFormat("function f(): List<any> {}");
868 }
869 
870 TEST_F(FormatTestJS, OptionalTypes) {
871   verifyFormat("function x(a?: b, c?, d?) {}");
872   verifyFormat("class X {\n"
873                "  y?: z;\n"
874                "  z?;\n"
875                "}");
876   verifyFormat("interface X {\n"
877                "  y?(): z;\n"
878                "}");
879   verifyFormat("x ? 1 : 2;");
880   verifyFormat("constructor({aa}: {\n"
881                "  aa?: string,\n"
882                "  aaaaaaaa?: string,\n"
883                "  aaaaaaaaaaaaaaa?: boolean,\n"
884                "  aaaaaa?: List<string>\n"
885                "}) {}");
886 }
887 
888 TEST_F(FormatTestJS, IndexSignature) {
889   verifyFormat("var x: {[k: string]: v};");
890 }
891 
892 } // end namespace tooling
893 } // end namespace clang
894