xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision f412e26d046cfe8666c5ce08b11a66ca44974abd)
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     std::string result = format(test::messUp(Code), Style);
53     EXPECT_EQ(Code.str(), result) << "Formatted:\n" << result;
54   }
55 };
56 
57 TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
58   verifyFormat("a == = b;");
59   verifyFormat("a != = b;");
60 
61   verifyFormat("a === b;");
62   verifyFormat("aaaaaaa ===\n    b;", getGoogleJSStyleWithColumns(10));
63   verifyFormat("a !== b;");
64   verifyFormat("aaaaaaa !==\n    b;", getGoogleJSStyleWithColumns(10));
65   verifyFormat("if (a + b + c +\n"
66                "        d !==\n"
67                "    e + f + g)\n"
68                "  q();",
69                getGoogleJSStyleWithColumns(20));
70 
71   verifyFormat("a >> >= b;");
72 
73   verifyFormat("a >>> b;");
74   verifyFormat("aaaaaaa >>>\n    b;", getGoogleJSStyleWithColumns(10));
75   verifyFormat("a >>>= b;");
76   verifyFormat("aaaaaaa >>>=\n    b;", getGoogleJSStyleWithColumns(10));
77   verifyFormat("if (a + b + c +\n"
78                "        d >>>\n"
79                "    e + f + g)\n"
80                "  q();",
81                getGoogleJSStyleWithColumns(20));
82   verifyFormat("var x = aaaaaaaaaa ?\n"
83                "    bbbbbb :\n"
84                "    ccc;",
85                getGoogleJSStyleWithColumns(20));
86 
87   verifyFormat("var b = a.map((x) => x + 1);");
88   verifyFormat("return ('aaa') in bbbb;");
89 
90   // ES6 spread operator.
91   verifyFormat("someFunction(...a);");
92   verifyFormat("var x = [1, ...a, 2];");
93 }
94 
95 TEST_F(FormatTestJS, UnderstandsAmpAmp) {
96   verifyFormat("e && e.SomeFunction();");
97 }
98 
99 TEST_F(FormatTestJS, LiteralOperatorsCanBeKeywords) {
100   verifyFormat("not.and.or.not_eq = 1;");
101 }
102 
103 TEST_F(FormatTestJS, ReservedWords) {
104   // JavaScript reserved words (aka keywords) are only illegal when used as
105   // Identifiers, but are legal as IdentifierNames.
106   verifyFormat("x.class.struct = 1;");
107   verifyFormat("x.case = 1;");
108   verifyFormat("x.interface = 1;");
109   verifyFormat("x = {\n"
110                "  a: 12,\n"
111                "  interface: 1,\n"
112                "  switch: 1,\n"
113                "};");
114   verifyFormat("var struct = 2;");
115   verifyFormat("var union = 2;");
116 }
117 
118 TEST_F(FormatTestJS, CppKeywords) {
119   // Make sure we don't mess stuff up because of C++ keywords.
120   verifyFormat("return operator && (aa);");
121 }
122 
123 TEST_F(FormatTestJS, ES6DestructuringAssignment) {
124   verifyFormat("var [a, b, c] = [1, 2, 3];");
125   verifyFormat("let [a, b, c] = [1, 2, 3];");
126   verifyFormat("var {a, b} = {a: 1, b: 2};");
127   verifyFormat("let {a, b} = {a: 1, b: 2};");
128 }
129 
130 TEST_F(FormatTestJS, ContainerLiterals) {
131   verifyFormat("var x = {y: function(a) { return a; }};");
132   verifyFormat("return {\n"
133                "  link: function() {\n"
134                "    f();  //\n"
135                "  }\n"
136                "};");
137   verifyFormat("return {\n"
138                "  a: a,\n"
139                "  link: function() {\n"
140                "    f();  //\n"
141                "  }\n"
142                "};");
143   verifyFormat("return {\n"
144                "  a: a,\n"
145                "  link: function() {\n"
146                "    f();  //\n"
147                "  },\n"
148                "  link: function() {\n"
149                "    f();  //\n"
150                "  }\n"
151                "};");
152   verifyFormat("var stuff = {\n"
153                "  // comment for update\n"
154                "  update: false,\n"
155                "  // comment for modules\n"
156                "  modules: false,\n"
157                "  // comment for tasks\n"
158                "  tasks: false\n"
159                "};");
160   verifyFormat("return {\n"
161                "  'finish':\n"
162                "      //\n"
163                "      a\n"
164                "};");
165   verifyFormat("var obj = {\n"
166                "  fooooooooo: function(x) {\n"
167                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
168                "  }\n"
169                "};");
170   // Simple object literal, as opposed to enum style below.
171   verifyFormat("var obj = {a: 123};");
172   // Enum style top level assignment.
173   verifyFormat("X = {\n  a: 123\n};");
174   verifyFormat("X.Y = {\n  a: 123\n};");
175   // But only on the top level, otherwise its a plain object literal assignment.
176   verifyFormat("function x() {\n"
177                "  y = {z: 1};\n"
178                "}");
179   verifyFormat("x = foo && {a: 123};");
180 
181   // Arrow functions in object literals.
182   verifyFormat("var x = {y: (a) => { return a; }};");
183   verifyFormat("var x = {y: (a) => a};");
184 
185   // Computed keys.
186   verifyFormat("var x = {[a]: 1, b: 2, [c]: 3};");
187   verifyFormat("var x = {\n"
188                "  [a]: 1,\n"
189                "  b: 2,\n"
190                "  [c]: 3,\n"
191                "};");
192 }
193 
194 TEST_F(FormatTestJS, MethodsInObjectLiterals) {
195   verifyFormat("var o = {\n"
196                "  value: 'test',\n"
197                "  get value() {  // getter\n"
198                "    return this.value;\n"
199                "  }\n"
200                "};");
201   verifyFormat("var o = {\n"
202                "  value: 'test',\n"
203                "  set value(val) {  // setter\n"
204                "    this.value = val;\n"
205                "  }\n"
206                "};");
207   verifyFormat("var o = {\n"
208                "  value: 'test',\n"
209                "  someMethod(val) {  // method\n"
210                "    doSomething(this.value + val);\n"
211                "  }\n"
212                "};");
213   verifyFormat("var o = {\n"
214                "  someMethod(val) {  // method\n"
215                "    doSomething(this.value + val);\n"
216                "  },\n"
217                "  someOtherMethod(val) {  // method\n"
218                "    doSomething(this.value + val);\n"
219                "  }\n"
220                "};");
221 }
222 
223 TEST_F(FormatTestJS, SpacesInContainerLiterals) {
224   verifyFormat("var arr = [1, 2, 3];");
225   verifyFormat("f({a: 1, b: 2, c: 3});");
226 
227   verifyFormat("var object_literal_with_long_name = {\n"
228                "  a: 'aaaaaaaaaaaaaaaaaa',\n"
229                "  b: 'bbbbbbbbbbbbbbbbbb'\n"
230                "};");
231 
232   verifyFormat("f({a: 1, b: 2, c: 3});",
233                getChromiumStyle(FormatStyle::LK_JavaScript));
234   verifyFormat("f({'a': [{}]});");
235 }
236 
237 TEST_F(FormatTestJS, SingleQuoteStrings) {
238   verifyFormat("this.function('', true);");
239 }
240 
241 TEST_F(FormatTestJS, GoogScopes) {
242   verifyFormat("goog.scope(function() {\n"
243                "var x = a.b;\n"
244                "var y = c.d;\n"
245                "});  // goog.scope");
246   verifyFormat("goog.scope(function() {\n"
247                "// test\n"
248                "var x = 0;\n"
249                "// test\n"
250                "});");
251 }
252 
253 TEST_F(FormatTestJS, GoogModules) {
254   verifyFormat("goog.module('this.is.really.absurdly.long');",
255                getGoogleJSStyleWithColumns(40));
256   verifyFormat("goog.require('this.is.really.absurdly.long');",
257                getGoogleJSStyleWithColumns(40));
258   verifyFormat("goog.provide('this.is.really.absurdly.long');",
259                getGoogleJSStyleWithColumns(40));
260   verifyFormat("var long = goog.require('this.is.really.absurdly.long');",
261                getGoogleJSStyleWithColumns(40));
262   verifyFormat("goog.setTestOnly('this.is.really.absurdly.long');",
263                getGoogleJSStyleWithColumns(40));
264 
265   // These should be wrapped normally.
266   verifyFormat(
267       "var MyLongClassName =\n"
268       "    goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
269 }
270 
271 TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
272   verifyFormat("function outer1(a, b) {\n"
273                "  function inner1(a, b) { return a; }\n"
274                "  inner1(a, b);\n"
275                "}\n"
276                "function outer2(a, b) {\n"
277                "  function inner2(a, b) { return a; }\n"
278                "  inner2(a, b);\n"
279                "}");
280   verifyFormat("function f() {}");
281 }
282 
283 TEST_F(FormatTestJS, ArrayLiterals) {
284   verifyFormat("var aaaaa: List<SomeThing> =\n"
285                "    [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];");
286   verifyFormat("return [\n"
287                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
288                "  bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
289                "  ccccccccccccccccccccccccccc\n"
290                "];");
291   verifyFormat("return [\n"
292                "  aaaa().bbbbbbbb('A'),\n"
293                "  aaaa().bbbbbbbb('B'),\n"
294                "  aaaa().bbbbbbbb('C'),\n"
295                "];");
296   verifyFormat("var someVariable = SomeFunction([\n"
297                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
298                "  bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
299                "  ccccccccccccccccccccccccccc\n"
300                "]);");
301   verifyFormat("var someVariable = SomeFunction([\n"
302                "  [aaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbb],\n"
303                "]);",
304                getGoogleJSStyleWithColumns(51));
305   verifyFormat("var someVariable = SomeFunction(aaaa, [\n"
306                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
307                "  bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
308                "  ccccccccccccccccccccccccccc\n"
309                "]);");
310   verifyFormat("var someVariable = SomeFunction(\n"
311                "    aaaa,\n"
312                "    [\n"
313                "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
314                "      bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
315                "      ccccccccccccccccccccccccccc\n"
316                "    ],\n"
317                "    aaaa);");
318   verifyFormat("var aaaa = aaaaa ||  // wrap\n"
319                "    [];");
320 
321   verifyFormat("someFunction([], {a: a});");
322 }
323 
324 TEST_F(FormatTestJS, ColumnLayoutForArrayLiterals) {
325   verifyFormat("var array = [\n"
326                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
327                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
328                "];");
329   verifyFormat("var array = someFunction([\n"
330                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
331                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
332                "]);");
333 }
334 
335 TEST_F(FormatTestJS, FunctionLiterals) {
336   verifyFormat("doFoo(function() {});");
337   verifyFormat("doFoo(function() { return 1; });");
338   verifyFormat("var func = function() {\n"
339                "  return 1;\n"
340                "};");
341   verifyFormat("var func =  //\n"
342                "    function() {\n"
343                "  return 1;\n"
344                "};");
345   verifyFormat("return {\n"
346                "  body: {\n"
347                "    setAttribute: function(key, val) { this[key] = val; },\n"
348                "    getAttribute: function(key) { return this[key]; },\n"
349                "    style: {direction: ''}\n"
350                "  }\n"
351                "};");
352   verifyFormat("abc = xyz ? function() {\n"
353                "  return 1;\n"
354                "} : function() {\n"
355                "  return -1;\n"
356                "};");
357 
358   verifyFormat("var closure = goog.bind(\n"
359                "    function() {  // comment\n"
360                "      foo();\n"
361                "      bar();\n"
362                "    },\n"
363                "    this, arg1IsReallyLongAndNeeedsLineBreaks,\n"
364                "    arg3IsReallyLongAndNeeedsLineBreaks);");
365   verifyFormat("var closure = goog.bind(function() {  // comment\n"
366                "  foo();\n"
367                "  bar();\n"
368                "}, this);");
369   verifyFormat("return {\n"
370                "  a: 'E',\n"
371                "  b: function() {\n"
372                "    return function() {\n"
373                "      f();  //\n"
374                "    };\n"
375                "  }\n"
376                "};");
377   verifyFormat("{\n"
378                "  var someVariable = function(x) {\n"
379                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
380                "  };\n"
381                "}");
382   verifyFormat("someLooooooooongFunction(\n"
383                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
384                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
385                "    function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
386                "      // code\n"
387                "    });");
388 
389   verifyFormat("f({a: function() { return 1; }});",
390                getGoogleJSStyleWithColumns(33));
391   verifyFormat("f({\n"
392                "  a: function() { return 1; }\n"
393                "});",
394                getGoogleJSStyleWithColumns(32));
395 
396   verifyFormat("return {\n"
397                "  a: function SomeFunction() {\n"
398                "    // ...\n"
399                "    return 1;\n"
400                "  }\n"
401                "};");
402   verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
403                "    .then(goog.bind(function(aaaaaaaaaaa) {\n"
404                "      someFunction();\n"
405                "      someFunction();\n"
406                "    }, this), aaaaaaaaaaaaaaaaa);");
407 
408   verifyFormat("someFunction(goog.bind(function() {\n"
409                "  doSomething();\n"
410                "  doSomething();\n"
411                "}, this), goog.bind(function() {\n"
412                "  doSomething();\n"
413                "  doSomething();\n"
414                "}, this));");
415 
416   // FIXME: This is bad, we should be wrapping before "function() {".
417   verifyFormat("someFunction(function() {\n"
418                "  doSomething();  // break\n"
419                "})\n"
420                "    .doSomethingElse(\n"
421                "        // break\n"
422                "        );");
423 }
424 
425 TEST_F(FormatTestJS, InliningFunctionLiterals) {
426   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
427   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
428   verifyFormat("var func = function() {\n"
429                "  return 1;\n"
430                "};",
431                Style);
432   verifyFormat("var func = doSomething(function() { return 1; });", Style);
433   verifyFormat("var outer = function() {\n"
434                "  var inner = function() { return 1; }\n"
435                "};",
436                Style);
437   verifyFormat("function outer1(a, b) {\n"
438                "  function inner1(a, b) { return a; }\n"
439                "}",
440                Style);
441 
442   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
443   verifyFormat("var func = function() { return 1; };", Style);
444   verifyFormat("var func = doSomething(function() { return 1; });", Style);
445   verifyFormat(
446       "var outer = function() { var inner = function() { return 1; } };",
447       Style);
448   verifyFormat("function outer1(a, b) {\n"
449                "  function inner1(a, b) { return a; }\n"
450                "}",
451                Style);
452 
453   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
454   verifyFormat("var func = function() {\n"
455                "  return 1;\n"
456                "};",
457                Style);
458   verifyFormat("var func = doSomething(function() {\n"
459                "  return 1;\n"
460                "});",
461                Style);
462   verifyFormat("var outer = function() {\n"
463                "  var inner = function() {\n"
464                "    return 1;\n"
465                "  }\n"
466                "};",
467                Style);
468   verifyFormat("function outer1(a, b) {\n"
469                "  function inner1(a, b) {\n"
470                "    return a;\n"
471                "  }\n"
472                "}",
473                Style);
474 
475   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
476   verifyFormat("var func = function() {\n"
477                "  return 1;\n"
478                "};",
479                Style);
480 }
481 
482 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
483   verifyFormat("promise.then(\n"
484                "    function success() {\n"
485                "      doFoo();\n"
486                "      doBar();\n"
487                "    },\n"
488                "    function error() {\n"
489                "      doFoo();\n"
490                "      doBaz();\n"
491                "    },\n"
492                "    []);\n");
493   verifyFormat("promise.then(\n"
494                "    function success() {\n"
495                "      doFoo();\n"
496                "      doBar();\n"
497                "    },\n"
498                "    [],\n"
499                "    function error() {\n"
500                "      doFoo();\n"
501                "      doBaz();\n"
502                "    });\n");
503   verifyFormat("promise.then(\n"
504                "    [],\n"
505                "    function success() {\n"
506                "      doFoo();\n"
507                "      doBar();\n"
508                "    },\n"
509                "    function error() {\n"
510                "      doFoo();\n"
511                "      doBaz();\n"
512                "    });\n");
513 
514   verifyFormat("getSomeLongPromise()\n"
515                "    .then(function(value) { body(); })\n"
516                "    .thenCatch(function(error) {\n"
517                "      body();\n"
518                "      body();\n"
519                "    });");
520   verifyFormat("getSomeLongPromise()\n"
521                "    .then(function(value) {\n"
522                "      body();\n"
523                "      body();\n"
524                "    })\n"
525                "    .thenCatch(function(error) {\n"
526                "      body();\n"
527                "      body();\n"
528                "    });");
529 
530   verifyFormat("getSomeLongPromise()\n"
531                "    .then(function(value) { body(); })\n"
532                "    .thenCatch(function(error) { body(); });");
533 }
534 
535 TEST_F(FormatTestJS, ArrowFunctions) {
536   verifyFormat("var x = (a) => {\n"
537                "  return a;\n"
538                "};");
539   verifyFormat("var x = (a) => {\n"
540                "  function y() { return 42; }\n"
541                "  return a;\n"
542                "};");
543   verifyFormat("var x = (a: type): {some: type} => {\n"
544                "  return a;\n"
545                "};");
546   verifyFormat("var x = (a) => a;");
547   verifyFormat("return () => [];");
548   verifyFormat("var aaaaaaaaaaaaaaaaaaaa = {\n"
549                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
550                "      (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
551                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) =>\n"
552                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
553                "};");
554   verifyFormat("var a = a.aaaaaaa(\n"
555                "    (a: a) => aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) &&\n"
556                "        aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
557   verifyFormat("var a = a.aaaaaaa(\n"
558                "    (a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) ?\n"
559                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb) :\n"
560                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
561 
562   // FIXME: This is bad, we should be wrapping before "() => {".
563   verifyFormat("someFunction(() => {\n"
564                "  doSomething();  // break\n"
565                "})\n"
566                "    .doSomethingElse(\n"
567                "        // break\n"
568                "        );");
569 }
570 
571 TEST_F(FormatTestJS, ReturnStatements) {
572   verifyFormat("function() {\n"
573                "  return [hello, world];\n"
574                "}");
575 }
576 
577 TEST_F(FormatTestJS, ForLoops) {
578   verifyFormat("for (var i in [2, 3]) {\n"
579                "}");
580 }
581 
582 TEST_F(FormatTestJS, AutomaticSemicolonInsertion) {
583   // The following statements must not wrap, as otherwise the program meaning
584   // would change due to automatic semicolon insertion.
585   // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
586   verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10));
587   verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10));
588   verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10));
589   verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
590   verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
591   verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
592 }
593 
594 TEST_F(FormatTestJS, ClosureStyleCasts) {
595   verifyFormat("var x = /** @type {foo} */ (bar);");
596 }
597 
598 TEST_F(FormatTestJS, TryCatch) {
599   verifyFormat("try {\n"
600                "  f();\n"
601                "} catch (e) {\n"
602                "  g();\n"
603                "} finally {\n"
604                "  h();\n"
605                "}");
606 
607   // But, of course, "catch" is a perfectly fine function name in JavaScript.
608   verifyFormat("someObject.catch();");
609   verifyFormat("someObject.new();");
610   verifyFormat("someObject.delete();");
611 }
612 
613 TEST_F(FormatTestJS, StringLiteralConcatenation) {
614   verifyFormat("var literal = 'hello ' +\n"
615                "    'world';");
616 }
617 
618 TEST_F(FormatTestJS, RegexLiteralClassification) {
619   // Regex literals.
620   verifyFormat("var regex = /abc/;");
621   verifyFormat("f(/abc/);");
622   verifyFormat("f(abc, /abc/);");
623   verifyFormat("some_map[/abc/];");
624   verifyFormat("var x = a ? /abc/ : /abc/;");
625   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
626   verifyFormat("var x = !/abc/.test(y);");
627   verifyFormat("var x = a && /abc/.test(y);");
628   verifyFormat("var x = a || /abc/.test(y);");
629   verifyFormat("var x = a + /abc/.search(y);");
630   verifyFormat("/abc/.search(y);");
631   verifyFormat("var regexs = {/abc/, /abc/};");
632   verifyFormat("return /abc/;");
633 
634   // Not regex literals.
635   verifyFormat("var a = a / 2 + b / 3;");
636   verifyFormat("var a = a++ / 2;");
637   // Prefix unary can operate on regex literals, not that it makes sense.
638   verifyFormat("var a = ++/a/;");
639 
640   // This is a known issue, regular expressions are incorrectly detected if
641   // directly following a closing parenthesis.
642   verifyFormat("if (foo) / bar /.exec(baz);");
643 }
644 
645 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
646   verifyFormat("var regex = /=/;");
647   verifyFormat("var regex = /a*/;");
648   verifyFormat("var regex = /a+/;");
649   verifyFormat("var regex = /a?/;");
650   verifyFormat("var regex = /.a./;");
651   verifyFormat("var regex = /a\\*/;");
652   verifyFormat("var regex = /^a$/;");
653   verifyFormat("var regex = /\\/a/;");
654   verifyFormat("var regex = /(?:x)/;");
655   verifyFormat("var regex = /x(?=y)/;");
656   verifyFormat("var regex = /x(?!y)/;");
657   verifyFormat("var regex = /x|y/;");
658   verifyFormat("var regex = /a{2}/;");
659   verifyFormat("var regex = /a{1,3}/;");
660 
661   verifyFormat("var regex = /[abc]/;");
662   verifyFormat("var regex = /[^abc]/;");
663   verifyFormat("var regex = /[\\b]/;");
664   verifyFormat("var regex = /[/]/;");
665   verifyFormat("var regex = /[\\/]/;");
666   verifyFormat("var regex = /\\[/;");
667   verifyFormat("var regex = /\\\\[/]/;");
668   verifyFormat("var regex = /}[\"]/;");
669   verifyFormat("var regex = /}[/\"]/;");
670   verifyFormat("var regex = /}[\"/]/;");
671 
672   verifyFormat("var regex = /\\b/;");
673   verifyFormat("var regex = /\\B/;");
674   verifyFormat("var regex = /\\d/;");
675   verifyFormat("var regex = /\\D/;");
676   verifyFormat("var regex = /\\f/;");
677   verifyFormat("var regex = /\\n/;");
678   verifyFormat("var regex = /\\r/;");
679   verifyFormat("var regex = /\\s/;");
680   verifyFormat("var regex = /\\S/;");
681   verifyFormat("var regex = /\\t/;");
682   verifyFormat("var regex = /\\v/;");
683   verifyFormat("var regex = /\\w/;");
684   verifyFormat("var regex = /\\W/;");
685   verifyFormat("var regex = /a(a)\\1/;");
686   verifyFormat("var regex = /\\0/;");
687   verifyFormat("var regex = /\\\\/g;");
688   verifyFormat("var regex = /\\a\\\\/g;");
689   verifyFormat("var regex = /\a\\//g;");
690   verifyFormat("var regex = /a\\//;\n"
691                "var x = 0;");
692   EXPECT_EQ("var regex = /'/g;", format("var regex = /'/g ;"));
693   EXPECT_EQ("var regex = /'/g;  //'", format("var regex = /'/g ; //'"));
694   EXPECT_EQ("var regex = /\\/*/;\n"
695             "var x = 0;",
696             format("var regex = /\\/*/;\n"
697                    "var x=0;"));
698   EXPECT_EQ("var x = /a\\//;", format("var x = /a\\//  \n;"));
699   verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
700   verifyFormat("var regex =\n"
701                "    /\"/;",
702                getGoogleJSStyleWithColumns(15));
703   verifyFormat("var regex =  //\n"
704                "    /a/;");
705   verifyFormat("var regexs = [\n"
706                "  /d/,   //\n"
707                "  /aa/,  //\n"
708                "];");
709 }
710 
711 TEST_F(FormatTestJS, RegexLiteralModifiers) {
712   verifyFormat("var regex = /abc/g;");
713   verifyFormat("var regex = /abc/i;");
714   verifyFormat("var regex = /abc/m;");
715   verifyFormat("var regex = /abc/y;");
716 }
717 
718 TEST_F(FormatTestJS, RegexLiteralLength) {
719   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
720                getGoogleJSStyleWithColumns(60));
721   verifyFormat("var regex =\n"
722                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
723                getGoogleJSStyleWithColumns(60));
724   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
725                getGoogleJSStyleWithColumns(50));
726 }
727 
728 TEST_F(FormatTestJS, RegexLiteralExamples) {
729   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
730 }
731 
732 TEST_F(FormatTestJS, TypeAnnotations) {
733   verifyFormat("var x: string;");
734   verifyFormat("function x(): string {\n  return 'x';\n}");
735   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
736   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
737   verifyFormat("for (var y: string in x) {\n  x();\n}");
738   verifyFormat("((a: string, b: number): string => a + b);");
739   verifyFormat("var x: (y: number) => string;");
740   verifyFormat("var x: P<string, (a: number) => string>;");
741   verifyFormat("var x = {y: function(): z { return 1; }};");
742   verifyFormat("var x = {y: function(): {a: number} { return 1; }};");
743   verifyFormat("function someFunc(args: string[]):\n"
744                "    {longReturnValue: string[]} {}",
745                getGoogleJSStyleWithColumns(60));
746 }
747 
748 TEST_F(FormatTestJS, ClassDeclarations) {
749   verifyFormat("class C {\n  x: string = 12;\n}");
750   verifyFormat("class C {\n  x(): string => 12;\n}");
751   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
752   verifyFormat("class C {\n  private x: string = 12;\n}");
753   verifyFormat("class C {\n  private static x: string = 12;\n}");
754   verifyFormat("class C {\n  static x(): string { return 'asd'; }\n}");
755   verifyFormat("class C extends P implements I {}");
756   verifyFormat("class C extends p.P implements i.I {}");
757   verifyFormat("class Test {\n"
758                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
759                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
760                "}");
761   verifyFormat("foo = class Name {\n"
762                "  constructor() {}\n"
763                "};");
764   verifyFormat("foo = class {\n"
765                "  constructor() {}\n"
766                "};");
767 
768   // ':' is not a type declaration here.
769   verifyFormat("class X {\n"
770                "  subs = {\n"
771                "    'b': {\n"
772                "      'c': 1,\n"
773                "    },\n"
774                "  };\n"
775                "}");
776 }
777 
778 TEST_F(FormatTestJS, InterfaceDeclarations) {
779   verifyFormat("interface I {\n"
780                "  x: string;\n"
781                "  enum: string[];\n"
782                "}\n"
783                "var y;");
784   // Ensure that state is reset after parsing the interface.
785   verifyFormat("interface a {}\n"
786                "export function b() {}\n"
787                "var x;");
788 
789   // Arrays of object type literals.
790   verifyFormat("interface I {\n"
791                "  o: {}[];\n"
792                "}");
793 }
794 
795 TEST_F(FormatTestJS, EnumDeclarations) {
796   verifyFormat("enum Foo {\n"
797                "  A = 1,\n"
798                "  B\n"
799                "}");
800   verifyFormat("export /* somecomment*/ enum Foo {\n"
801                "  A = 1,\n"
802                "  B\n"
803                "}");
804   verifyFormat("enum Foo {\n"
805                "  A = 1,  // comment\n"
806                "  B\n"
807                "}\n"
808                "var x = 1;");
809 }
810 
811 TEST_F(FormatTestJS, MetadataAnnotations) {
812   verifyFormat("@A\nclass C {\n}");
813   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
814   verifyFormat("@A\n@B\nclass C {\n}");
815   verifyFormat("class C {\n  @A x: string;\n}");
816   verifyFormat("class C {\n"
817                "  @A\n"
818                "  private x(): string {\n"
819                "    return 'y';\n"
820                "  }\n"
821                "}");
822   verifyFormat("class X {}\n"
823                "class Y {}");
824 }
825 
826 TEST_F(FormatTestJS, Modules) {
827   verifyFormat("import SomeThing from 'some/module.js';");
828   verifyFormat("import {X, Y} from 'some/module.js';");
829   verifyFormat("import a, {X, Y} from 'some/module.js';");
830   verifyFormat("import {\n"
831                "  VeryLongImportsAreAnnoying,\n"
832                "  VeryLongImportsAreAnnoying,\n"
833                "  VeryLongImportsAreAnnoying,\n"
834                "  VeryLongImportsAreAnnoying\n"
835                "} from 'some/module.js';");
836   verifyFormat("import {\n"
837                "  X,\n"
838                "  Y,\n"
839                "} from 'some/module.js';");
840   verifyFormat("import {\n"
841                "  X,\n"
842                "  Y,\n"
843                "} from 'some/long/module.js';",
844                getGoogleJSStyleWithColumns(20));
845   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
846   verifyFormat("import * as lib from 'some/module.js';");
847   verifyFormat("var x = {import: 1};\nx.import = 2;");
848 
849   verifyFormat("export function fn() {\n"
850                "  return 'fn';\n"
851                "}");
852   verifyFormat("export function A() {}\n"
853                "export default function B() {}\n"
854                "export function C() {}");
855   verifyFormat("export const x = 12;");
856   verifyFormat("export default class X {}");
857   verifyFormat("export {X, Y} from 'some/module.js';");
858   verifyFormat("export {\n"
859                "  X,\n"
860                "  Y,\n"
861                "} from 'some/module.js';");
862   verifyFormat("export class C {\n"
863                "  x: number;\n"
864                "  y: string;\n"
865                "}");
866   verifyFormat("export class X { y: number; }");
867   verifyFormat("export default class X { y: number }");
868   verifyFormat("export default function() {\n  return 1;\n}");
869   verifyFormat("export var x = 12;");
870   verifyFormat("class C {}\n"
871                "export function f() {}\n"
872                "var v;");
873   verifyFormat("export var x: number = 12;");
874   verifyFormat("export const y = {\n"
875                "  a: 1,\n"
876                "  b: 2\n"
877                "};");
878   verifyFormat("export enum Foo {\n"
879                "  BAR,\n"
880                "  // adsdasd\n"
881                "  BAZ\n"
882                "}");
883   verifyFormat("export default [\n"
884                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
885                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
886                "];");
887   verifyFormat("export default [];");
888   verifyFormat("export default () => {};");
889 }
890 
891 TEST_F(FormatTestJS, TemplateStrings) {
892   // Keeps any whitespace/indentation within the template string.
893   EXPECT_EQ("var x = `hello\n"
894             "     ${  name    }\n"
895             "  !`;",
896             format("var x    =    `hello\n"
897                    "     ${  name    }\n"
898                    "  !`;"));
899 
900   verifyFormat("var x =\n"
901                "    `hello ${world}` >= some();",
902                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
903   verifyFormat("var x = `hello ${world}` >= some();",
904                getGoogleJSStyleWithColumns(35)); // Barely fits.
905   EXPECT_EQ("var x = `hello\n"
906             "  ${world}` >=\n"
907             "    some();",
908             format("var x =\n"
909                    "    `hello\n"
910                    "  ${world}` >= some();",
911                    getGoogleJSStyleWithColumns(21))); // Barely doesn't fit.
912   EXPECT_EQ("var x = `hello\n"
913             "  ${world}` >= some();",
914             format("var x =\n"
915                    "    `hello\n"
916                    "  ${world}` >= some();",
917                    getGoogleJSStyleWithColumns(22))); // Barely fits.
918 
919   verifyFormat("var x =\n"
920                "    `h`;",
921                getGoogleJSStyleWithColumns(11));
922   EXPECT_EQ(
923       "var x =\n    `multi\n  line`;",
924       format("var x = `multi\n  line`;", getGoogleJSStyleWithColumns(13)));
925   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
926                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
927 
928   // Make sure template strings get a proper ColumnWidth assigned, even if they
929   // are first token in line.
930   verifyFormat(
931       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
932       "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
933 
934   // Two template strings.
935   verifyFormat("var x = `hello` == `hello`;");
936 
937   // Comments in template strings.
938   EXPECT_EQ("var x = `//a`;\n"
939             "var y;",
940             format("var x =\n `//a`;\n"
941                    "var y  ;"));
942   EXPECT_EQ("var x = `/*a`;\n"
943             "var y;",
944             format("var x =\n `/*a`;\n"
945                    "var y;"));
946   // Unterminated string literals in a template string.
947   verifyFormat("var x = `'`;  // comment with matching quote '\n"
948                "var y;");
949   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
950                "var y;");
951   // Backticks in a comment - not a template string.
952   EXPECT_EQ("var x = 1  // `/*a`;\n"
953             "    ;",
954             format("var x =\n 1  // `/*a`;\n"
955                    "    ;"));
956   EXPECT_EQ("/* ` */ var x = 1; /* ` */",
957             format("/* ` */ var x\n= 1; /* ` */"));
958   // Comment spans multiple template strings.
959   EXPECT_EQ("var x = `/*a`;\n"
960             "var y = ` */ `;",
961             format("var x =\n `/*a`;\n"
962                    "var y =\n ` */ `;"));
963   // Escaped backtick.
964   EXPECT_EQ("var x = ` \\` a`;\n"
965             "var y;",
966             format("var x = ` \\` a`;\n"
967                    "var y;"));
968 }
969 
970 TEST_F(FormatTestJS, CastSyntax) { verifyFormat("var x = <type>foo;"); }
971 
972 TEST_F(FormatTestJS, TypeArguments) {
973   verifyFormat("class X<Y> {}");
974   verifyFormat("new X<Y>();");
975   verifyFormat("foo<Y>(a);");
976   verifyFormat("var x: X<Y>[];");
977   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
978   verifyFormat("function f(a: List<any> = null) {}");
979   verifyFormat("function f(): List<any> {}");
980   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
981                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
982   verifyFormat("function aaaaaaaaaa(\n"
983                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
984                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
985                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
986 }
987 
988 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
989   verifyFormat(
990       "function foo(check: Object):\n"
991       "    check is {foo: string, bar: string, baz: string, foobar: string} {\n"
992       "  return 'bar' in check;\n"
993       "}\n");
994 }
995 
996 TEST_F(FormatTestJS, OptionalTypes) {
997   verifyFormat("function x(a?: b, c?, d?) {}");
998   verifyFormat("class X {\n"
999                "  y?: z;\n"
1000                "  z?;\n"
1001                "}");
1002   verifyFormat("interface X {\n"
1003                "  y?(): z;\n"
1004                "}");
1005   verifyFormat("x ? 1 : 2;");
1006   verifyFormat("constructor({aa}: {\n"
1007                "  aa?: string,\n"
1008                "  aaaaaaaa?: string,\n"
1009                "  aaaaaaaaaaaaaaa?: boolean,\n"
1010                "  aaaaaa?: List<string>\n"
1011                "}) {}");
1012 }
1013 
1014 TEST_F(FormatTestJS, IndexSignature) {
1015   verifyFormat("var x: {[k: string]: v};");
1016 }
1017 
1018 TEST_F(FormatTestJS, WrapAfterParen) {
1019   verifyFormat("xxxxxxxxxxx(\n"
1020                "    aaa, aaa);",
1021                getGoogleJSStyleWithColumns(20));
1022   verifyFormat("xxxxxxxxxxx(\n"
1023                "    aaa, aaa, aaa,\n"
1024                "    aaa, aaa, aaa);",
1025                getGoogleJSStyleWithColumns(20));
1026   verifyFormat("xxxxxxxxxxx(\n"
1027                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
1028                "    function(x) {\n"
1029                "      y();  //\n"
1030                "    });",
1031                getGoogleJSStyleWithColumns(40));
1032   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
1033                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
1034 }
1035 
1036 TEST_F(FormatTestJS, JSDocAnnotations) {
1037   EXPECT_EQ("/**\n"
1038             " * @export {this.is.a.long.path.to.a.Type}\n"
1039             " */",
1040             format("/**\n"
1041                    " * @export {this.is.a.long.path.to.a.Type}\n"
1042                    " */",
1043                    getGoogleJSStyleWithColumns(20)));
1044 }
1045 
1046 } // end namespace tooling
1047 } // end namespace clang
1048