xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision 259188b1b58e9441d0aff11537a589b61ce611ed)
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, ClosureStyleCasts) {
525   verifyFormat("var x = /** @type {foo} */ (bar);");
526 }
527 
528 TEST_F(FormatTestJS, TryCatch) {
529   verifyFormat("try {\n"
530                "  f();\n"
531                "} catch (e) {\n"
532                "  g();\n"
533                "} finally {\n"
534                "  h();\n"
535                "}");
536 
537   // But, of course, "catch" is a perfectly fine function name in JavaScript.
538   verifyFormat("someObject.catch();");
539   verifyFormat("someObject.new();");
540   verifyFormat("someObject.delete();");
541 }
542 
543 TEST_F(FormatTestJS, StringLiteralConcatenation) {
544   verifyFormat("var literal = 'hello ' +\n"
545                "              'world';");
546 }
547 
548 TEST_F(FormatTestJS, RegexLiteralClassification) {
549   // Regex literals.
550   verifyFormat("var regex = /abc/;");
551   verifyFormat("f(/abc/);");
552   verifyFormat("f(abc, /abc/);");
553   verifyFormat("some_map[/abc/];");
554   verifyFormat("var x = a ? /abc/ : /abc/;");
555   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
556   verifyFormat("var x = !/abc/.test(y);");
557   verifyFormat("var x = a && /abc/.test(y);");
558   verifyFormat("var x = a || /abc/.test(y);");
559   verifyFormat("var x = a + /abc/.search(y);");
560   verifyFormat("var regexs = {/abc/, /abc/};");
561   verifyFormat("return /abc/;");
562 
563   // Not regex literals.
564   verifyFormat("var a = a / 2 + b / 3;");
565 }
566 
567 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
568   verifyFormat("var regex = /=/;");
569   verifyFormat("var regex = /a*/;");
570   verifyFormat("var regex = /a+/;");
571   verifyFormat("var regex = /a?/;");
572   verifyFormat("var regex = /.a./;");
573   verifyFormat("var regex = /a\\*/;");
574   verifyFormat("var regex = /^a$/;");
575   verifyFormat("var regex = /\\/a/;");
576   verifyFormat("var regex = /(?:x)/;");
577   verifyFormat("var regex = /x(?=y)/;");
578   verifyFormat("var regex = /x(?!y)/;");
579   verifyFormat("var regex = /x|y/;");
580   verifyFormat("var regex = /a{2}/;");
581   verifyFormat("var regex = /a{1,3}/;");
582   verifyFormat("var regex = /[abc]/;");
583   verifyFormat("var regex = /[^abc]/;");
584   verifyFormat("var regex = /[\\b]/;");
585   verifyFormat("var regex = /\\b/;");
586   verifyFormat("var regex = /\\B/;");
587   verifyFormat("var regex = /\\d/;");
588   verifyFormat("var regex = /\\D/;");
589   verifyFormat("var regex = /\\f/;");
590   verifyFormat("var regex = /\\n/;");
591   verifyFormat("var regex = /\\r/;");
592   verifyFormat("var regex = /\\s/;");
593   verifyFormat("var regex = /\\S/;");
594   verifyFormat("var regex = /\\t/;");
595   verifyFormat("var regex = /\\v/;");
596   verifyFormat("var regex = /\\w/;");
597   verifyFormat("var regex = /\\W/;");
598   verifyFormat("var regex = /a(a)\\1/;");
599   verifyFormat("var regex = /\\0/;");
600   verifyFormat("var regex = /\\\\/g;");
601   verifyFormat("var regex = /\\a\\\\/g;");
602   verifyFormat("var regex = /\a\\//g;");
603   verifyFormat("var regex = /a\\//;\n"
604                "var x = 0;");
605   EXPECT_EQ("var regex = /\\/*/;\n"
606             "var x = 0;",
607             format("var regex = /\\/*/;\n"
608                    "var x=0;"));
609 }
610 
611 TEST_F(FormatTestJS, RegexLiteralModifiers) {
612   verifyFormat("var regex = /abc/g;");
613   verifyFormat("var regex = /abc/i;");
614   verifyFormat("var regex = /abc/m;");
615   verifyFormat("var regex = /abc/y;");
616 }
617 
618 TEST_F(FormatTestJS, RegexLiteralLength) {
619   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
620                getGoogleJSStyleWithColumns(60));
621   verifyFormat("var regex =\n"
622                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
623                getGoogleJSStyleWithColumns(60));
624   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
625                getGoogleJSStyleWithColumns(50));
626 }
627 
628 TEST_F(FormatTestJS, RegexLiteralExamples) {
629   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
630 }
631 
632 TEST_F(FormatTestJS, TypeAnnotations) {
633   verifyFormat("var x: string;");
634   verifyFormat("function x(): string {\n  return 'x';\n}");
635   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
636   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
637   verifyFormat("for (var y: string in x) {\n  x();\n}");
638   verifyFormat("((a: string, b: number): string => a + b);");
639   verifyFormat("var x: (y: number) => string;");
640   verifyFormat("var x: P<string, (a: number) => string>;");
641   verifyFormat("var x = {y: function(): z { return 1; }};");
642   verifyFormat("var x = {y: function(): {a: number} { return 1; }};");
643 }
644 
645 TEST_F(FormatTestJS, ClassDeclarations) {
646   verifyFormat("class C {\n  x: string = 12;\n}");
647   verifyFormat("class C {\n  x(): string => 12;\n}");
648   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
649   verifyFormat("class C {\n  private x: string = 12;\n}");
650   verifyFormat("class C {\n  private static x: string = 12;\n}");
651   verifyFormat("class C {\n  static x(): string { return 'asd'; }\n}");
652   verifyFormat("class C extends P implements I {}");
653   verifyFormat("class C extends p.P implements i.I {}");
654 
655   // ':' is not a type declaration here.
656   verifyFormat("class X {\n"
657                "  subs = {\n"
658                "    'b': {\n"
659                "      'c': 1,\n"
660                "    },\n"
661                "  };\n"
662                "}");
663 }
664 
665 TEST_F(FormatTestJS, InterfaceDeclarations) {
666   verifyFormat("interface I {\n"
667                "  x: string;\n"
668                "}\n"
669                "var y;");
670 }
671 
672 TEST_F(FormatTestJS, MetadataAnnotations) {
673   verifyFormat("@A\nclass C {\n}");
674   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
675   verifyFormat("@A\n@B\nclass C {\n}");
676   verifyFormat("class C {\n  @A x: string;\n}");
677   verifyFormat("class C {\n"
678                "  @A\n"
679                "  private x(): string {\n"
680                "    return 'y';\n"
681                "  }\n"
682                "}");
683   verifyFormat("class X {}\n"
684                "class Y {}");
685 }
686 
687 TEST_F(FormatTestJS, Modules) {
688   verifyFormat("import SomeThing from 'some/module.js';");
689   verifyFormat("import {X, Y} from 'some/module.js';");
690   verifyFormat("import {\n"
691                "  VeryLongImportsAreAnnoying,\n"
692                "  VeryLongImportsAreAnnoying,\n"
693                "  VeryLongImportsAreAnnoying,\n"
694                "  VeryLongImportsAreAnnoying\n"
695                "} from 'some/module.js';");
696   verifyFormat("import {\n"
697                "  X,\n"
698                "  Y,\n"
699                "} from 'some/module.js';");
700   verifyFormat("import {\n"
701                "  X,\n"
702                "  Y,\n"
703                "} from 'some/long/module.js';",
704                getGoogleJSStyleWithColumns(20));
705   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
706   verifyFormat("import * as lib from 'some/module.js';");
707   verifyFormat("var x = {import: 1};\nx.import = 2;");
708 
709   verifyFormat("export function fn() {\n"
710                "  return 'fn';\n"
711                "}");
712   verifyFormat("export function A() {}\n"
713                "export default function B() {}\n"
714                "export function C() {}");
715   verifyFormat("export const x = 12;");
716   verifyFormat("export default class X {}");
717   verifyFormat("export {X, Y} from 'some/module.js';");
718   verifyFormat("export {\n"
719                "  X,\n"
720                "  Y,\n"
721                "} from 'some/module.js';");
722   verifyFormat("export class C {\n"
723                "  x: number;\n"
724                "  y: string;\n"
725                "}");
726   verifyFormat("export class X { y: number; }");
727   verifyFormat("export default class X { y: number }");
728   verifyFormat("export default function() {\n  return 1;\n}");
729   verifyFormat("export var x = 12;");
730   verifyFormat("class C {}\n"
731                "export function f() {}\n"
732                "var v;");
733   verifyFormat("export var x: number = 12;");
734   verifyFormat("export const y = {\n"
735                "  a: 1,\n"
736                "  b: 2\n"
737                "};");
738 }
739 
740 TEST_F(FormatTestJS, TemplateStrings) {
741   // Keeps any whitespace/indentation within the template string.
742   EXPECT_EQ("var x = `hello\n"
743             "     ${  name    }\n"
744             "  !`;",
745             format("var x    =    `hello\n"
746                    "     ${  name    }\n"
747                    "  !`;"));
748 
749   // FIXME: +1 / -1 offsets are to work around clang-format miscalculating
750   // widths for unknown tokens that are not whitespace (e.g. '`'). Remove when
751   // the code is corrected.
752 
753   verifyFormat("var x =\n"
754                "    `hello ${world}` >= some();",
755                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
756   verifyFormat("var x = `hello ${world}` >= some();",
757                getGoogleJSStyleWithColumns(35 + 1)); // Barely fits.
758   EXPECT_EQ("var x = `hello\n"
759             "  ${world}` >=\n"
760             "        some();",
761             format("var x =\n"
762                    "    `hello\n"
763                    "  ${world}` >= some();",
764                    getGoogleJSStyleWithColumns(21))); // Barely doesn't fit.
765   EXPECT_EQ("var x = `hello\n"
766             "  ${world}` >= some();",
767             format("var x =\n"
768                    "    `hello\n"
769                    "  ${world}` >= some();",
770                    getGoogleJSStyleWithColumns(22))); // Barely fits.
771 
772   verifyFormat("var x =\n    `h`;", getGoogleJSStyleWithColumns(13 - 1));
773   EXPECT_EQ(
774       "var x =\n    `multi\n  line`;",
775       format("var x = `multi\n  line`;", getGoogleJSStyleWithColumns(14 - 1)));
776 
777   // Make sure template strings get a proper ColumnWidth assigned, even if they
778   // are first token in line.
779   verifyFormat(
780       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
781       "        `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
782 
783   // Two template strings.
784   verifyFormat("var x = `hello` == `hello`;");
785 
786   // Comments in template strings.
787   EXPECT_EQ("var x = `//a`;\n"
788             "var y;",
789             format("var x =\n `//a`;\n"
790                    "var y  ;"));
791   EXPECT_EQ("var x = `/*a`;\n"
792             "var y;",
793             format("var x =\n `/*a`;\n"
794                    "var y;"));
795   // Backticks in a comment - not a template string.
796   EXPECT_EQ("var x = 1  // `/*a`;\n"
797             "    ;",
798             format("var x =\n 1  // `/*a`;\n"
799                    "    ;"));
800   EXPECT_EQ("/* ` */ var x = 1; /* ` */",
801             format("/* ` */ var x\n= 1; /* ` */"));
802   // Comment spans multiple template strings.
803   EXPECT_EQ("var x = `/*a`;\n"
804             "var y = ` */ `;",
805             format("var x =\n `/*a`;\n"
806                    "var y =\n ` */ `;"));
807   // Escaped backtick.
808   EXPECT_EQ("var x = ` \\` a`;\n"
809             "var y;",
810             format("var x = ` \\` a`;\n"
811                    "var y;"));
812 }
813 
814 TEST_F(FormatTestJS, CastSyntax) {
815   verifyFormat("var x = <type>foo;");
816 }
817 
818 TEST_F(FormatTestJS, TypeArguments) {
819   verifyFormat("class X<Y> {}");
820   verifyFormat("new X<Y>();");
821   verifyFormat("foo<Y>(a);");
822   verifyFormat("var x: X<Y>[];");
823   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
824   verifyFormat("function f(a: List<any> = null) {}");
825   verifyFormat("function f(): List<any> {}");
826 }
827 
828 TEST_F(FormatTestJS, OptionalTypes) {
829   verifyFormat("function x(a?: b, c?, d?) {}");
830   verifyFormat("class X {\n"
831                "  y?: z;\n"
832                "  z?;\n"
833                "}");
834   verifyFormat("interface X {\n"
835                "  y?(): z;\n"
836                "}");
837   verifyFormat("x ? 1 : 2;");
838   verifyFormat("constructor({aa}: {\n"
839                "  aa?: string,\n"
840                "  aaaaaaaa?: string,\n"
841                "  aaaaaaaaaaaaaaa?: boolean,\n"
842                "  aaaaaa?: List<string>\n"
843                "}) {}");
844 }
845 
846 TEST_F(FormatTestJS, IndexSignature) {
847   verifyFormat("var x: {[k: string]: v};");
848 }
849 
850 } // end namespace tooling
851 } // end namespace clang
852