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