xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision d196abbba3ea1b6872539e628cc4fabd49e6b1ee)
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 }
744 
745 TEST_F(FormatTestJS, ClassDeclarations) {
746   verifyFormat("class C {\n  x: string = 12;\n}");
747   verifyFormat("class C {\n  x(): string => 12;\n}");
748   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
749   verifyFormat("class C {\n  private x: string = 12;\n}");
750   verifyFormat("class C {\n  private static x: string = 12;\n}");
751   verifyFormat("class C {\n  static x(): string { return 'asd'; }\n}");
752   verifyFormat("class C extends P implements I {}");
753   verifyFormat("class C extends p.P implements i.I {}");
754   verifyFormat("class Test {\n"
755                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
756                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
757                "}");
758   verifyFormat("foo = class Name {\n"
759                "  constructor() {}\n"
760                "};");
761   verifyFormat("foo = class {\n"
762                "  constructor() {}\n"
763                "};");
764 
765   // ':' is not a type declaration here.
766   verifyFormat("class X {\n"
767                "  subs = {\n"
768                "    'b': {\n"
769                "      'c': 1,\n"
770                "    },\n"
771                "  };\n"
772                "}");
773 }
774 
775 TEST_F(FormatTestJS, InterfaceDeclarations) {
776   verifyFormat("interface I {\n"
777                "  x: string;\n"
778                "  enum: string[];\n"
779                "}\n"
780                "var y;");
781   // Ensure that state is reset after parsing the interface.
782   verifyFormat("interface a {}\n"
783                "export function b() {}\n"
784                "var x;");
785 
786   // Arrays of object type literals.
787   verifyFormat("interface I {\n"
788                "  o: {}[];\n"
789                "}");
790 }
791 
792 TEST_F(FormatTestJS, EnumDeclarations) {
793   verifyFormat("enum Foo {\n"
794                "  A = 1,\n"
795                "  B\n"
796                "}");
797   verifyFormat("export /* somecomment*/ enum Foo {\n"
798                "  A = 1,\n"
799                "  B\n"
800                "}");
801   verifyFormat("enum Foo {\n"
802                "  A = 1,  // comment\n"
803                "  B\n"
804                "}\n"
805                "var x = 1;");
806 }
807 
808 TEST_F(FormatTestJS, MetadataAnnotations) {
809   verifyFormat("@A\nclass C {\n}");
810   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
811   verifyFormat("@A\n@B\nclass C {\n}");
812   verifyFormat("class C {\n  @A x: string;\n}");
813   verifyFormat("class C {\n"
814                "  @A\n"
815                "  private x(): string {\n"
816                "    return 'y';\n"
817                "  }\n"
818                "}");
819   verifyFormat("class X {}\n"
820                "class Y {}");
821 }
822 
823 TEST_F(FormatTestJS, Modules) {
824   verifyFormat("import SomeThing from 'some/module.js';");
825   verifyFormat("import {X, Y} from 'some/module.js';");
826   verifyFormat("import a, {X, Y} from 'some/module.js';");
827   verifyFormat("import {\n"
828                "  VeryLongImportsAreAnnoying,\n"
829                "  VeryLongImportsAreAnnoying,\n"
830                "  VeryLongImportsAreAnnoying,\n"
831                "  VeryLongImportsAreAnnoying\n"
832                "} from 'some/module.js';");
833   verifyFormat("import {\n"
834                "  X,\n"
835                "  Y,\n"
836                "} from 'some/module.js';");
837   verifyFormat("import {\n"
838                "  X,\n"
839                "  Y,\n"
840                "} from 'some/long/module.js';",
841                getGoogleJSStyleWithColumns(20));
842   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
843   verifyFormat("import * as lib from 'some/module.js';");
844   verifyFormat("var x = {import: 1};\nx.import = 2;");
845 
846   verifyFormat("export function fn() {\n"
847                "  return 'fn';\n"
848                "}");
849   verifyFormat("export function A() {}\n"
850                "export default function B() {}\n"
851                "export function C() {}");
852   verifyFormat("export const x = 12;");
853   verifyFormat("export default class X {}");
854   verifyFormat("export {X, Y} from 'some/module.js';");
855   verifyFormat("export {\n"
856                "  X,\n"
857                "  Y,\n"
858                "} from 'some/module.js';");
859   verifyFormat("export class C {\n"
860                "  x: number;\n"
861                "  y: string;\n"
862                "}");
863   verifyFormat("export class X { y: number; }");
864   verifyFormat("export default class X { y: number }");
865   verifyFormat("export default function() {\n  return 1;\n}");
866   verifyFormat("export var x = 12;");
867   verifyFormat("class C {}\n"
868                "export function f() {}\n"
869                "var v;");
870   verifyFormat("export var x: number = 12;");
871   verifyFormat("export const y = {\n"
872                "  a: 1,\n"
873                "  b: 2\n"
874                "};");
875   verifyFormat("export enum Foo {\n"
876                "  BAR,\n"
877                "  // adsdasd\n"
878                "  BAZ\n"
879                "}");
880   verifyFormat("export default [\n"
881                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
882                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
883                "];");
884   verifyFormat("export default [];");
885   verifyFormat("export default () => {};");
886 }
887 
888 TEST_F(FormatTestJS, TemplateStrings) {
889   // Keeps any whitespace/indentation within the template string.
890   EXPECT_EQ("var x = `hello\n"
891             "     ${  name    }\n"
892             "  !`;",
893             format("var x    =    `hello\n"
894                    "     ${  name    }\n"
895                    "  !`;"));
896 
897   verifyFormat("var x =\n"
898                "    `hello ${world}` >= some();",
899                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
900   verifyFormat("var x = `hello ${world}` >= some();",
901                getGoogleJSStyleWithColumns(35)); // Barely fits.
902   EXPECT_EQ("var x = `hello\n"
903             "  ${world}` >=\n"
904             "    some();",
905             format("var x =\n"
906                    "    `hello\n"
907                    "  ${world}` >= some();",
908                    getGoogleJSStyleWithColumns(21))); // Barely doesn't fit.
909   EXPECT_EQ("var x = `hello\n"
910             "  ${world}` >= some();",
911             format("var x =\n"
912                    "    `hello\n"
913                    "  ${world}` >= some();",
914                    getGoogleJSStyleWithColumns(22))); // Barely fits.
915 
916   verifyFormat("var x =\n"
917                "    `h`;",
918                getGoogleJSStyleWithColumns(11));
919   EXPECT_EQ(
920       "var x =\n    `multi\n  line`;",
921       format("var x = `multi\n  line`;", getGoogleJSStyleWithColumns(13)));
922   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
923                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
924 
925   // Make sure template strings get a proper ColumnWidth assigned, even if they
926   // are first token in line.
927   verifyFormat(
928       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
929       "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
930 
931   // Two template strings.
932   verifyFormat("var x = `hello` == `hello`;");
933 
934   // Comments in template strings.
935   EXPECT_EQ("var x = `//a`;\n"
936             "var y;",
937             format("var x =\n `//a`;\n"
938                    "var y  ;"));
939   EXPECT_EQ("var x = `/*a`;\n"
940             "var y;",
941             format("var x =\n `/*a`;\n"
942                    "var y;"));
943   // Unterminated string literals in a template string.
944   verifyFormat("var x = `'`;  // comment with matching quote '\n"
945                "var y;");
946   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
947                "var y;");
948   // Backticks in a comment - not a template string.
949   EXPECT_EQ("var x = 1  // `/*a`;\n"
950             "    ;",
951             format("var x =\n 1  // `/*a`;\n"
952                    "    ;"));
953   EXPECT_EQ("/* ` */ var x = 1; /* ` */",
954             format("/* ` */ var x\n= 1; /* ` */"));
955   // Comment spans multiple template strings.
956   EXPECT_EQ("var x = `/*a`;\n"
957             "var y = ` */ `;",
958             format("var x =\n `/*a`;\n"
959                    "var y =\n ` */ `;"));
960   // Escaped backtick.
961   EXPECT_EQ("var x = ` \\` a`;\n"
962             "var y;",
963             format("var x = ` \\` a`;\n"
964                    "var y;"));
965 }
966 
967 TEST_F(FormatTestJS, CastSyntax) { verifyFormat("var x = <type>foo;"); }
968 
969 TEST_F(FormatTestJS, TypeArguments) {
970   verifyFormat("class X<Y> {}");
971   verifyFormat("new X<Y>();");
972   verifyFormat("foo<Y>(a);");
973   verifyFormat("var x: X<Y>[];");
974   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
975   verifyFormat("function f(a: List<any> = null) {}");
976   verifyFormat("function f(): List<any> {}");
977   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
978                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
979   verifyFormat("function aaaaaaaaaa(\n"
980                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
981                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
982                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
983 }
984 
985 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
986   verifyFormat(
987       "function foo(check: Object):\n"
988       "    check is {foo: string, bar: string, baz: string, foobar: string} {\n"
989       "  return 'bar' in check;\n"
990       "}\n");
991 }
992 
993 TEST_F(FormatTestJS, OptionalTypes) {
994   verifyFormat("function x(a?: b, c?, d?) {}");
995   verifyFormat("class X {\n"
996                "  y?: z;\n"
997                "  z?;\n"
998                "}");
999   verifyFormat("interface X {\n"
1000                "  y?(): z;\n"
1001                "}");
1002   verifyFormat("x ? 1 : 2;");
1003   verifyFormat("constructor({aa}: {\n"
1004                "  aa?: string,\n"
1005                "  aaaaaaaa?: string,\n"
1006                "  aaaaaaaaaaaaaaa?: boolean,\n"
1007                "  aaaaaa?: List<string>\n"
1008                "}) {}");
1009 }
1010 
1011 TEST_F(FormatTestJS, IndexSignature) {
1012   verifyFormat("var x: {[k: string]: v};");
1013 }
1014 
1015 TEST_F(FormatTestJS, WrapAfterParen) {
1016   verifyFormat("xxxxxxxxxxx(\n"
1017                "    aaa, aaa);",
1018                getGoogleJSStyleWithColumns(20));
1019   verifyFormat("xxxxxxxxxxx(\n"
1020                "    aaa, aaa, aaa,\n"
1021                "    aaa, aaa, aaa);",
1022                getGoogleJSStyleWithColumns(20));
1023   verifyFormat("xxxxxxxxxxx(\n"
1024                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
1025                "    function(x) {\n"
1026                "      y();  //\n"
1027                "    });",
1028                getGoogleJSStyleWithColumns(40));
1029   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
1030                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
1031 }
1032 
1033 TEST_F(FormatTestJS, JSDocAnnotations) {
1034   EXPECT_EQ("/**\n"
1035             " * @export {this.is.a.long.path.to.a.Type}\n"
1036             " */",
1037             format("/**\n"
1038                    " * @export {this.is.a.long.path.to.a.Type}\n"
1039                    " */",
1040                    getGoogleJSStyleWithColumns(20)));
1041 }
1042 
1043 } // end namespace tooling
1044 } // end namespace clang
1045