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