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