xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision 3b86534a63b89d691f03476d209ae196bd778d84)
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     FormattingAttemptStatus Status;
28     tooling::Replacements Replaces =
29         reformat(Style, Code, Ranges, "<stdin>", &Status);
30     EXPECT_TRUE(Status.FormatComplete);
31     auto Result = applyAllReplacements(Code, Replaces);
32     EXPECT_TRUE(static_cast<bool>(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   static void verifyFormat(
57       llvm::StringRef Expected,
58       llvm::StringRef Code,
59       const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
60     std::string Result = format(Code, Style);
61     EXPECT_EQ(Expected.str(), Result) << "Formatted:\n" << Result;
62   }
63 };
64 
65 TEST_F(FormatTestJS, BlockComments) {
66   verifyFormat("/* aaaaaaaaaaaaa */ aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
67                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
68 }
69 
70 TEST_F(FormatTestJS, JSDocComments) {
71   // Break the first line of a multiline jsdoc comment.
72   EXPECT_EQ("/**\n"
73             " * jsdoc line 1\n"
74             " * jsdoc line 2\n"
75             " */",
76             format("/** jsdoc line 1\n"
77                    " * jsdoc line 2\n"
78                    " */",
79                    getGoogleJSStyleWithColumns(20)));
80   // Both break after '/**' and break the line itself.
81   EXPECT_EQ("/**\n"
82             " * jsdoc line long\n"
83             " * long jsdoc line 2\n"
84             " */",
85             format("/** jsdoc line long long\n"
86                    " * jsdoc line 2\n"
87                    " */",
88                    getGoogleJSStyleWithColumns(20)));
89   // Break a short first line if the ending '*/' is on a newline.
90   EXPECT_EQ("/**\n"
91             " * jsdoc line 1\n"
92             " */",
93             format("/** jsdoc line 1\n"
94                    " */", getGoogleJSStyleWithColumns(20)));
95   // Don't break the first line of a short single line jsdoc comment.
96   EXPECT_EQ("/** jsdoc line 1 */",
97             format("/** jsdoc line 1 */", getGoogleJSStyleWithColumns(20)));
98   // Don't break the first line of a single line jsdoc comment if it just fits
99   // the column limit.
100   EXPECT_EQ("/** jsdoc line 12 */",
101             format("/** jsdoc line 12 */", getGoogleJSStyleWithColumns(20)));
102   // Don't break after '/**' and before '*/' if there is no space between
103   // '/**' and the content.
104   EXPECT_EQ(
105       "/*** nonjsdoc long\n"
106       " * line */",
107       format("/*** nonjsdoc long line */", getGoogleJSStyleWithColumns(20)));
108   EXPECT_EQ(
109       "/**strange long long\n"
110       " * line */",
111       format("/**strange long long line */", getGoogleJSStyleWithColumns(20)));
112   // Break the first line of a single line jsdoc comment if it just exceeds the
113   // column limit.
114   EXPECT_EQ("/**\n"
115             " * jsdoc line 123\n"
116             " */",
117             format("/** jsdoc line 123 */", getGoogleJSStyleWithColumns(20)));
118   // Break also if the leading indent of the first line is more than 1 column.
119   EXPECT_EQ("/**\n"
120             " * jsdoc line 123\n"
121             " */",
122             format("/**  jsdoc line 123 */", getGoogleJSStyleWithColumns(20)));
123   // Break also if the leading indent of the first line is more than 1 column.
124   EXPECT_EQ("/**\n"
125             " * jsdoc line 123\n"
126             " */",
127             format("/**   jsdoc line 123 */", getGoogleJSStyleWithColumns(20)));
128   // Break after the content of the last line.
129   EXPECT_EQ("/**\n"
130             " * line 1\n"
131             " * line 2\n"
132             " */",
133             format("/**\n"
134                    " * line 1\n"
135                    " * line 2 */",
136                    getGoogleJSStyleWithColumns(20)));
137   // Break both the content and after the content of the last line.
138   EXPECT_EQ("/**\n"
139             " * line 1\n"
140             " * line long long\n"
141             " * long\n"
142             " */",
143             format("/**\n"
144                    " * line 1\n"
145                    " * line long long long */",
146                    getGoogleJSStyleWithColumns(20)));
147 
148   // The comment block gets indented.
149   EXPECT_EQ("function f() {\n"
150             "  /**\n"
151             "   * comment about\n"
152             "   * x\n"
153             "   */\n"
154             "  var x = 1;\n"
155             "}",
156             format("function f() {\n"
157                    "/** comment about x */\n"
158                    "var x = 1;\n"
159                    "}",
160                    getGoogleJSStyleWithColumns(20)));
161 
162   // Don't break the first line of a single line short jsdoc comment pragma.
163   EXPECT_EQ("/** @returns j */",
164             format("/** @returns j */",
165                    getGoogleJSStyleWithColumns(20)));
166 
167   // Break a single line long jsdoc comment pragma.
168   EXPECT_EQ("/**\n"
169             " * @returns {string} jsdoc line 12\n"
170             " */",
171             format("/** @returns {string} jsdoc line 12 */",
172                    getGoogleJSStyleWithColumns(20)));
173 
174   EXPECT_EQ("/**\n"
175             " * @returns {string} jsdoc line 12\n"
176             " */",
177             format("/** @returns {string} jsdoc line 12  */",
178                    getGoogleJSStyleWithColumns(20)));
179 
180   EXPECT_EQ("/**\n"
181             " * @returns {string} jsdoc line 12\n"
182             " */",
183             format("/** @returns {string} jsdoc line 12*/",
184                    getGoogleJSStyleWithColumns(20)));
185 
186   // Fix a multiline jsdoc comment ending in a comment pragma.
187   EXPECT_EQ("/**\n"
188             " * line 1\n"
189             " * line 2\n"
190             " * @returns {string} jsdoc line 12\n"
191             " */",
192             format("/** line 1\n"
193                    " * line 2\n"
194                    " * @returns {string} jsdoc line 12 */",
195                    getGoogleJSStyleWithColumns(20)));
196 
197   EXPECT_EQ("/**\n"
198             " * line 1\n"
199             " * line 2\n"
200             " *\n"
201             " * @returns j\n"
202             " */",
203             format("/** line 1\n"
204                    " * line 2\n"
205                    " *\n"
206                    " * @returns j */",
207                    getGoogleJSStyleWithColumns(20)));
208 }
209 
210 TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
211   verifyFormat("a == = b;");
212   verifyFormat("a != = b;");
213 
214   verifyFormat("a === b;");
215   verifyFormat("aaaaaaa ===\n    b;", getGoogleJSStyleWithColumns(10));
216   verifyFormat("a !== b;");
217   verifyFormat("aaaaaaa !==\n    b;", getGoogleJSStyleWithColumns(10));
218   verifyFormat("if (a + b + c +\n"
219                "        d !==\n"
220                "    e + f + g)\n"
221                "  q();",
222                getGoogleJSStyleWithColumns(20));
223 
224   verifyFormat("a >> >= b;");
225 
226   verifyFormat("a >>> b;");
227   verifyFormat("aaaaaaa >>>\n    b;", getGoogleJSStyleWithColumns(10));
228   verifyFormat("a >>>= b;");
229   verifyFormat("aaaaaaa >>>=\n    b;", getGoogleJSStyleWithColumns(10));
230   verifyFormat("if (a + b + c +\n"
231                "        d >>>\n"
232                "    e + f + g)\n"
233                "  q();",
234                getGoogleJSStyleWithColumns(20));
235   verifyFormat("var x = aaaaaaaaaa ?\n"
236                "    bbbbbb :\n"
237                "    ccc;",
238                getGoogleJSStyleWithColumns(20));
239 
240   verifyFormat("var b = a.map((x) => x + 1);");
241   verifyFormat("return ('aaa') in bbbb;");
242   verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
243                "    aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
244   FormatStyle Style = getGoogleJSStyleWithColumns(80);
245   Style.AlignOperands = true;
246   verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
247                "        aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
248                Style);
249   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
250   verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa()\n"
251                "            in aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
252                Style);
253 
254   // ES6 spread operator.
255   verifyFormat("someFunction(...a);");
256   verifyFormat("var x = [1, ...a, 2];");
257 }
258 
259 TEST_F(FormatTestJS, UnderstandsAmpAmp) {
260   verifyFormat("e && e.SomeFunction();");
261 }
262 
263 TEST_F(FormatTestJS, LiteralOperatorsCanBeKeywords) {
264   verifyFormat("not.and.or.not_eq = 1;");
265 }
266 
267 TEST_F(FormatTestJS, ReservedWords) {
268   // JavaScript reserved words (aka keywords) are only illegal when used as
269   // Identifiers, but are legal as IdentifierNames.
270   verifyFormat("x.class.struct = 1;");
271   verifyFormat("x.case = 1;");
272   verifyFormat("x.interface = 1;");
273   verifyFormat("x.for = 1;");
274   verifyFormat("x.of() = 1;");
275   verifyFormat("of(null);");
276   verifyFormat("import {of} from 'x';");
277   verifyFormat("x.in() = 1;");
278   verifyFormat("x.let() = 1;");
279   verifyFormat("x.var() = 1;");
280   verifyFormat("x.for() = 1;");
281   verifyFormat("x.as() = 1;");
282   verifyFormat("x = {\n"
283                "  a: 12,\n"
284                "  interface: 1,\n"
285                "  switch: 1,\n"
286                "};");
287   verifyFormat("var struct = 2;");
288   verifyFormat("var union = 2;");
289   verifyFormat("var interface = 2;");
290   verifyFormat("interface = 2;");
291   verifyFormat("x = interface instanceof y;");
292   verifyFormat("interface Test {\n"
293                "  x: string;\n"
294                "  switch: string;\n"
295                "  case: string;\n"
296                "  default: string;\n"
297                "}\n");
298 }
299 
300 TEST_F(FormatTestJS, ReservedWordsMethods) {
301   verifyFormat(
302       "class X {\n"
303       "  delete() {\n"
304       "    x();\n"
305       "  }\n"
306       "  interface() {\n"
307       "    x();\n"
308       "  }\n"
309       "  let() {\n"
310       "    x();\n"
311       "  }\n"
312       "}\n");
313 }
314 
315 TEST_F(FormatTestJS, ReservedWordsParenthesized) {
316   // All of these are statements using the keyword, not function calls.
317   verifyFormat("throw (x + y);\n"
318                "await (await x).y;\n"
319                "typeof (x) === 'string';\n"
320                "void (0);\n"
321                "delete (x.y);\n"
322                "return (x);\n");
323 }
324 
325 TEST_F(FormatTestJS, CppKeywords) {
326   // Make sure we don't mess stuff up because of C++ keywords.
327   verifyFormat("return operator && (aa);");
328   // .. or QT ones.
329   verifyFormat("slots: Slot[];");
330 }
331 
332 TEST_F(FormatTestJS, ES6DestructuringAssignment) {
333   verifyFormat("var [a, b, c] = [1, 2, 3];");
334   verifyFormat("const [a, b, c] = [1, 2, 3];");
335   verifyFormat("let [a, b, c] = [1, 2, 3];");
336   verifyFormat("var {a, b} = {a: 1, b: 2};");
337   verifyFormat("let {a, b} = {a: 1, b: 2};");
338 }
339 
340 TEST_F(FormatTestJS, ContainerLiterals) {
341   verifyFormat("var x = {\n"
342                "  y: function(a) {\n"
343                "    return a;\n"
344                "  }\n"
345                "};");
346   verifyFormat("return {\n"
347                "  link: function() {\n"
348                "    f();  //\n"
349                "  }\n"
350                "};");
351   verifyFormat("return {\n"
352                "  a: a,\n"
353                "  link: function() {\n"
354                "    f();  //\n"
355                "  }\n"
356                "};");
357   verifyFormat("return {\n"
358                "  a: a,\n"
359                "  link: function() {\n"
360                "    f();  //\n"
361                "  },\n"
362                "  link: function() {\n"
363                "    f();  //\n"
364                "  }\n"
365                "};");
366   verifyFormat("var stuff = {\n"
367                "  // comment for update\n"
368                "  update: false,\n"
369                "  // comment for modules\n"
370                "  modules: false,\n"
371                "  // comment for tasks\n"
372                "  tasks: false\n"
373                "};");
374   verifyFormat("return {\n"
375                "  'finish':\n"
376                "      //\n"
377                "      a\n"
378                "};");
379   verifyFormat("var obj = {\n"
380                "  fooooooooo: function(x) {\n"
381                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
382                "  }\n"
383                "};");
384   // Simple object literal, as opposed to enum style below.
385   verifyFormat("var obj = {a: 123};");
386   // Enum style top level assignment.
387   verifyFormat("X = {\n  a: 123\n};");
388   verifyFormat("X.Y = {\n  a: 123\n};");
389   // But only on the top level, otherwise its a plain object literal assignment.
390   verifyFormat("function x() {\n"
391                "  y = {z: 1};\n"
392                "}");
393   verifyFormat("x = foo && {a: 123};");
394 
395   // Arrow functions in object literals.
396   verifyFormat("var x = {\n"
397                "  y: (a) => {\n"
398                "    return a;\n"
399                "  }\n"
400                "};");
401   verifyFormat("var x = {y: (a) => a};");
402 
403   // Methods in object literals.
404   verifyFormat("var x = {\n"
405                "  y(a: string): number {\n"
406                "    return a;\n"
407                "  }\n"
408                "};");
409   verifyFormat("var x = {\n"
410                "  y(a: string) {\n"
411                "    return a;\n"
412                "  }\n"
413                "};");
414 
415   // Computed keys.
416   verifyFormat("var x = {[a]: 1, b: 2, [c]: 3};");
417   verifyFormat("var x = {\n"
418                "  [a]: 1,\n"
419                "  b: 2,\n"
420                "  [c]: 3,\n"
421                "};");
422 
423   // Object literals can leave out labels.
424   verifyFormat("f({a}, () => {\n"
425                "  g();  //\n"
426                "});");
427 
428   // Keys can be quoted.
429   verifyFormat("var x = {\n"
430                "  a: a,\n"
431                "  b: b,\n"
432                "  'c': c,\n"
433                "};");
434 
435   // Dict literals can skip the label names.
436   verifyFormat("var x = {\n"
437                "  aaa,\n"
438                "  aaa,\n"
439                "  aaa,\n"
440                "};");
441   verifyFormat("return {\n"
442                "  a,\n"
443                "  b: 'b',\n"
444                "  c,\n"
445                "};");
446 }
447 
448 TEST_F(FormatTestJS, MethodsInObjectLiterals) {
449   verifyFormat("var o = {\n"
450                "  value: 'test',\n"
451                "  get value() {  // getter\n"
452                "    return this.value;\n"
453                "  }\n"
454                "};");
455   verifyFormat("var o = {\n"
456                "  value: 'test',\n"
457                "  set value(val) {  // setter\n"
458                "    this.value = val;\n"
459                "  }\n"
460                "};");
461   verifyFormat("var o = {\n"
462                "  value: 'test',\n"
463                "  someMethod(val) {  // method\n"
464                "    doSomething(this.value + val);\n"
465                "  }\n"
466                "};");
467   verifyFormat("var o = {\n"
468                "  someMethod(val) {  // method\n"
469                "    doSomething(this.value + val);\n"
470                "  },\n"
471                "  someOtherMethod(val) {  // method\n"
472                "    doSomething(this.value + val);\n"
473                "  }\n"
474                "};");
475 }
476 
477 TEST_F(FormatTestJS, GettersSettersVisibilityKeywords) {
478   // Don't break after "protected"
479   verifyFormat("class X {\n"
480                "  protected get getter():\n"
481                "      number {\n"
482                "    return 1;\n"
483                "  }\n"
484                "}",
485                getGoogleJSStyleWithColumns(12));
486   // Don't break after "get"
487   verifyFormat("class X {\n"
488                "  protected get someReallyLongGetterName():\n"
489                "      number {\n"
490                "    return 1;\n"
491                "  }\n"
492                "}",
493                getGoogleJSStyleWithColumns(40));
494 }
495 
496 TEST_F(FormatTestJS, SpacesInContainerLiterals) {
497   verifyFormat("var arr = [1, 2, 3];");
498   verifyFormat("f({a: 1, b: 2, c: 3});");
499 
500   verifyFormat("var object_literal_with_long_name = {\n"
501                "  a: 'aaaaaaaaaaaaaaaaaa',\n"
502                "  b: 'bbbbbbbbbbbbbbbbbb'\n"
503                "};");
504 
505   verifyFormat("f({a: 1, b: 2, c: 3});",
506                getChromiumStyle(FormatStyle::LK_JavaScript));
507   verifyFormat("f({'a': [{}]});");
508 }
509 
510 TEST_F(FormatTestJS, SingleQuotedStrings) {
511   verifyFormat("this.function('', true);");
512 }
513 
514 TEST_F(FormatTestJS, GoogScopes) {
515   verifyFormat("goog.scope(function() {\n"
516                "var x = a.b;\n"
517                "var y = c.d;\n"
518                "});  // goog.scope");
519   verifyFormat("goog.scope(function() {\n"
520                "// test\n"
521                "var x = 0;\n"
522                "// test\n"
523                "});");
524 }
525 
526 TEST_F(FormatTestJS, IIFEs) {
527   // Internal calling parens; no semi.
528   verifyFormat("(function() {\n"
529                "var a = 1;\n"
530                "}())");
531   // External calling parens; no semi.
532   verifyFormat("(function() {\n"
533                "var b = 2;\n"
534                "})()");
535   // Internal calling parens; with semi.
536   verifyFormat("(function() {\n"
537                "var c = 3;\n"
538                "}());");
539   // External calling parens; with semi.
540   verifyFormat("(function() {\n"
541                "var d = 4;\n"
542                "})();");
543 }
544 
545 TEST_F(FormatTestJS, GoogModules) {
546   verifyFormat("goog.module('this.is.really.absurdly.long');",
547                getGoogleJSStyleWithColumns(40));
548   verifyFormat("goog.require('this.is.really.absurdly.long');",
549                getGoogleJSStyleWithColumns(40));
550   verifyFormat("goog.provide('this.is.really.absurdly.long');",
551                getGoogleJSStyleWithColumns(40));
552   verifyFormat("var long = goog.require('this.is.really.absurdly.long');",
553                getGoogleJSStyleWithColumns(40));
554   verifyFormat("goog.setTestOnly('this.is.really.absurdly.long');",
555                getGoogleJSStyleWithColumns(40));
556   verifyFormat("goog.forwardDeclare('this.is.really.absurdly.long');",
557                getGoogleJSStyleWithColumns(40));
558 
559   // These should be wrapped normally.
560   verifyFormat(
561       "var MyLongClassName =\n"
562       "    goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
563 }
564 
565 TEST_F(FormatTestJS, FormatsNamespaces) {
566   verifyFormat("namespace Foo {\n"
567                "  export let x = 1;\n"
568                "}\n");
569   verifyFormat("declare namespace Foo {\n"
570                "  export let x: number;\n"
571                "}\n");
572 }
573 
574 TEST_F(FormatTestJS, NamespacesMayNotWrap) {
575   verifyFormat("declare namespace foobarbaz {\n"
576                "}\n", getGoogleJSStyleWithColumns(18));
577   verifyFormat("declare module foobarbaz {\n"
578                "}\n", getGoogleJSStyleWithColumns(15));
579   verifyFormat("namespace foobarbaz {\n"
580                "}\n", getGoogleJSStyleWithColumns(10));
581   verifyFormat("module foobarbaz {\n"
582                "}\n", getGoogleJSStyleWithColumns(7));
583 }
584 
585 TEST_F(FormatTestJS, AmbientDeclarations) {
586   FormatStyle NineCols = getGoogleJSStyleWithColumns(9);
587   verifyFormat(
588       "declare class\n"
589       "    X {}",
590       NineCols);
591   verifyFormat(
592       "declare function\n"
593       "x();",  // TODO(martinprobst): should ideally be indented.
594       NineCols);
595   verifyFormat("declare function foo();\n"
596                "let x = 1;\n");
597   verifyFormat("declare function foo(): string;\n"
598                "let x = 1;\n");
599   verifyFormat("declare function foo(): {x: number};\n"
600                "let x = 1;\n");
601   verifyFormat("declare class X {}\n"
602                "let x = 1;\n");
603   verifyFormat("declare interface Y {}\n"
604                "let x = 1;\n");
605   verifyFormat(
606       "declare enum X {\n"
607       "}",
608       NineCols);
609   verifyFormat(
610       "declare let\n"
611       "    x: number;",
612       NineCols);
613 }
614 
615 TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
616   verifyFormat("function outer1(a, b) {\n"
617                "  function inner1(a, b) {\n"
618                "    return a;\n"
619                "  }\n"
620                "  inner1(a, b);\n"
621                "}\n"
622                "function outer2(a, b) {\n"
623                "  function inner2(a, b) {\n"
624                "    return a;\n"
625                "  }\n"
626                "  inner2(a, b);\n"
627                "}");
628   verifyFormat("function f() {}");
629   verifyFormat("function aFunction() {}\n"
630                "(function f() {\n"
631                "  var x = 1;\n"
632                "}());\n");
633   verifyFormat("function aFunction() {}\n"
634                "{\n"
635                "  let x = 1;\n"
636                "  console.log(x);\n"
637                "}\n");
638 }
639 
640 TEST_F(FormatTestJS, GeneratorFunctions) {
641   verifyFormat("function* f() {\n"
642                "  let x = 1;\n"
643                "  yield x;\n"
644                "  yield* something();\n"
645                "  yield [1, 2];\n"
646                "  yield {a: 1};\n"
647                "}");
648   verifyFormat("function*\n"
649                "    f() {\n"
650                "}",
651                getGoogleJSStyleWithColumns(8));
652   verifyFormat("export function* f() {\n"
653                "  yield 1;\n"
654                "}\n");
655   verifyFormat("class X {\n"
656                "  * generatorMethod() {\n"
657                "    yield x;\n"
658                "  }\n"
659                "}");
660   verifyFormat("var x = {\n"
661                "  a: function*() {\n"
662                "    //\n"
663                "  }\n"
664                "}\n");
665 }
666 
667 TEST_F(FormatTestJS, AsyncFunctions) {
668   verifyFormat("async function f() {\n"
669                "  let x = 1;\n"
670                "  return fetch(x);\n"
671                "}");
672   verifyFormat("async function f() {\n"
673                "  return 1;\n"
674                "}\n"
675                "\n"
676                "function a() {\n"
677                "  return 1;\n"
678                "}\n",
679                "  async   function f() {\n"
680                "   return 1;\n"
681                "}\n"
682                "\n"
683                "   function a() {\n"
684                "  return   1;\n"
685                "}  \n");
686   verifyFormat("async function* f() {\n"
687                "  yield fetch(x);\n"
688                "}");
689   verifyFormat("export async function f() {\n"
690                "  return fetch(x);\n"
691                "}");
692   verifyFormat("let x = async () => f();");
693   verifyFormat("let x = async function() {\n"
694                "  f();\n"
695                "};");
696   verifyFormat("let x = async();");
697   verifyFormat("class X {\n"
698                "  async asyncMethod() {\n"
699                "    return fetch(1);\n"
700                "  }\n"
701                "}");
702   verifyFormat("function initialize() {\n"
703                "  // Comment.\n"
704                "  return async.then();\n"
705                "}\n");
706   verifyFormat("for await (const x of y) {\n"
707                "  console.log(x);\n"
708                "}\n");
709   verifyFormat("function asyncLoop() {\n"
710                "  for await (const x of y) {\n"
711                "    console.log(x);\n"
712                "  }\n"
713                "}\n");
714 }
715 
716 TEST_F(FormatTestJS, FunctionParametersTrailingComma) {
717   verifyFormat("function trailingComma(\n"
718                "    p1,\n"
719                "    p2,\n"
720                "    p3,\n"
721                ") {\n"
722                "  a;  //\n"
723                "}\n",
724                "function trailingComma(p1, p2, p3,) {\n"
725                "  a;  //\n"
726                "}\n");
727   verifyFormat("trailingComma(\n"
728                "    p1,\n"
729                "    p2,\n"
730                "    p3,\n"
731                ");\n",
732                "trailingComma(p1, p2, p3,);\n");
733   verifyFormat("trailingComma(\n"
734                "    p1  // hello\n"
735                ");\n",
736                "trailingComma(p1 // hello\n"
737                ");\n");
738 }
739 
740 TEST_F(FormatTestJS, ArrayLiterals) {
741   verifyFormat("var aaaaa: List<SomeThing> =\n"
742                "    [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];");
743   verifyFormat("return [\n"
744                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
745                "  ccccccccccccccccccccccccccc\n"
746                "];");
747   verifyFormat("return [\n"
748                "  aaaa().bbbbbbbb('A'),\n"
749                "  aaaa().bbbbbbbb('B'),\n"
750                "  aaaa().bbbbbbbb('C'),\n"
751                "];");
752   verifyFormat("var someVariable = SomeFunction([\n"
753                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
754                "  ccccccccccccccccccccccccccc\n"
755                "]);");
756   verifyFormat("var someVariable = SomeFunction([\n"
757                "  [aaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbb],\n"
758                "]);",
759                getGoogleJSStyleWithColumns(51));
760   verifyFormat("var someVariable = SomeFunction(aaaa, [\n"
761                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
762                "  ccccccccccccccccccccccccccc\n"
763                "]);");
764   verifyFormat("var someVariable = SomeFunction(\n"
765                "    aaaa,\n"
766                "    [\n"
767                "      aaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
768                "      cccccccccccccccccccccccccc\n"
769                "    ],\n"
770                "    aaaa);");
771   verifyFormat("var aaaa = aaaaa ||  // wrap\n"
772                "    [];");
773 
774   verifyFormat("someFunction([], {a: a});");
775 
776   verifyFormat("var string = [\n"
777                "  'aaaaaa',\n"
778                "  'bbbbbb',\n"
779                "].join('+');");
780 }
781 
782 TEST_F(FormatTestJS, ColumnLayoutForArrayLiterals) {
783   verifyFormat("var array = [\n"
784                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
785                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
786                "];");
787   verifyFormat("var array = someFunction([\n"
788                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
789                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
790                "]);");
791 }
792 
793 TEST_F(FormatTestJS, FunctionLiterals) {
794   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
795   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
796   verifyFormat("doFoo(function() {});");
797   verifyFormat("doFoo(function() { return 1; });", Style);
798   verifyFormat("var func = function() {\n"
799                "  return 1;\n"
800                "};");
801   verifyFormat("var func =  //\n"
802                "    function() {\n"
803                "  return 1;\n"
804                "};");
805   verifyFormat("return {\n"
806                "  body: {\n"
807                "    setAttribute: function(key, val) { this[key] = val; },\n"
808                "    getAttribute: function(key) { return this[key]; },\n"
809                "    style: {direction: ''}\n"
810                "  }\n"
811                "};",
812                Style);
813   verifyFormat("abc = xyz ? function() {\n"
814                "  return 1;\n"
815                "} : function() {\n"
816                "  return -1;\n"
817                "};");
818 
819   verifyFormat("var closure = goog.bind(\n"
820                "    function() {  // comment\n"
821                "      foo();\n"
822                "      bar();\n"
823                "    },\n"
824                "    this, arg1IsReallyLongAndNeedsLineBreaks,\n"
825                "    arg3IsReallyLongAndNeedsLineBreaks);");
826   verifyFormat("var closure = goog.bind(function() {  // comment\n"
827                "  foo();\n"
828                "  bar();\n"
829                "}, this);");
830   verifyFormat("return {\n"
831                "  a: 'E',\n"
832                "  b: function() {\n"
833                "    return function() {\n"
834                "      f();  //\n"
835                "    };\n"
836                "  }\n"
837                "};");
838   verifyFormat("{\n"
839                "  var someVariable = function(x) {\n"
840                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
841                "  };\n"
842                "}");
843   verifyFormat("someLooooooooongFunction(\n"
844                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
845                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
846                "    function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
847                "      // code\n"
848                "    });");
849 
850   verifyFormat("return {\n"
851                "  a: function SomeFunction() {\n"
852                "    // ...\n"
853                "    return 1;\n"
854                "  }\n"
855                "};");
856   verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
857                "    .then(goog.bind(function(aaaaaaaaaaa) {\n"
858                "      someFunction();\n"
859                "      someFunction();\n"
860                "    }, this), aaaaaaaaaaaaaaaaa);");
861 
862   verifyFormat("someFunction(goog.bind(function() {\n"
863                "  doSomething();\n"
864                "  doSomething();\n"
865                "}, this), goog.bind(function() {\n"
866                "  doSomething();\n"
867                "  doSomething();\n"
868                "}, this));");
869 
870   verifyFormat("SomeFunction(function() {\n"
871                "  foo();\n"
872                "  bar();\n"
873                "}.bind(this));");
874 
875   verifyFormat("SomeFunction((function() {\n"
876                "               foo();\n"
877                "               bar();\n"
878                "             }).bind(this));");
879 
880   // FIXME: This is bad, we should be wrapping before "function() {".
881   verifyFormat("someFunction(function() {\n"
882                "  doSomething();  // break\n"
883                "})\n"
884                "    .doSomethingElse(\n"
885                "        // break\n"
886                "    );");
887 
888   Style.ColumnLimit = 33;
889   verifyFormat("f({a: function() { return 1; }});", Style);
890   Style.ColumnLimit = 32;
891   verifyFormat("f({\n"
892                "  a: function() { return 1; }\n"
893                "});",
894                Style);
895 
896 }
897 
898 TEST_F(FormatTestJS, DontWrapEmptyLiterals) {
899   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
900                "    .and.returnValue(Observable.of([]));");
901   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
902                "    .and.returnValue(Observable.of({}));");
903   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
904                "    .and.returnValue(Observable.of(()));");
905 }
906 
907 TEST_F(FormatTestJS, InliningFunctionLiterals) {
908   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
909   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
910   verifyFormat("var func = function() {\n"
911                "  return 1;\n"
912                "};",
913                Style);
914   verifyFormat("var func = doSomething(function() { return 1; });", Style);
915   verifyFormat("var outer = function() {\n"
916                "  var inner = function() { return 1; }\n"
917                "};",
918                Style);
919   verifyFormat("function outer1(a, b) {\n"
920                "  function inner1(a, b) { return a; }\n"
921                "}",
922                Style);
923 
924   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
925   verifyFormat("var func = function() { return 1; };", Style);
926   verifyFormat("var func = doSomething(function() { return 1; });", Style);
927   verifyFormat(
928       "var outer = function() { var inner = function() { return 1; } };",
929       Style);
930   verifyFormat("function outer1(a, b) {\n"
931                "  function inner1(a, b) { return a; }\n"
932                "}",
933                Style);
934 
935   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
936   verifyFormat("var func = function() {\n"
937                "  return 1;\n"
938                "};",
939                Style);
940   verifyFormat("var func = doSomething(function() {\n"
941                "  return 1;\n"
942                "});",
943                Style);
944   verifyFormat("var outer = function() {\n"
945                "  var inner = function() {\n"
946                "    return 1;\n"
947                "  }\n"
948                "};",
949                Style);
950   verifyFormat("function outer1(a, b) {\n"
951                "  function inner1(a, b) {\n"
952                "    return a;\n"
953                "  }\n"
954                "}",
955                Style);
956 
957   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
958   verifyFormat("var func = function() {\n"
959                "  return 1;\n"
960                "};",
961                Style);
962 }
963 
964 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
965   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
966   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
967   verifyFormat("promise.then(\n"
968                "    function success() {\n"
969                "      doFoo();\n"
970                "      doBar();\n"
971                "    },\n"
972                "    function error() {\n"
973                "      doFoo();\n"
974                "      doBaz();\n"
975                "    },\n"
976                "    []);\n");
977   verifyFormat("promise.then(\n"
978                "    function success() {\n"
979                "      doFoo();\n"
980                "      doBar();\n"
981                "    },\n"
982                "    [],\n"
983                "    function error() {\n"
984                "      doFoo();\n"
985                "      doBaz();\n"
986                "    });\n");
987   verifyFormat("promise.then(\n"
988                "    [],\n"
989                "    function success() {\n"
990                "      doFoo();\n"
991                "      doBar();\n"
992                "    },\n"
993                "    function error() {\n"
994                "      doFoo();\n"
995                "      doBaz();\n"
996                "    });\n");
997 
998   verifyFormat("getSomeLongPromise()\n"
999                "    .then(function(value) { body(); })\n"
1000                "    .thenCatch(function(error) {\n"
1001                "      body();\n"
1002                "      body();\n"
1003                "    });",
1004                Style);
1005   verifyFormat("getSomeLongPromise()\n"
1006                "    .then(function(value) {\n"
1007                "      body();\n"
1008                "      body();\n"
1009                "    })\n"
1010                "    .thenCatch(function(error) {\n"
1011                "      body();\n"
1012                "      body();\n"
1013                "    });");
1014 
1015   verifyFormat("getSomeLongPromise()\n"
1016                "    .then(function(value) { body(); })\n"
1017                "    .thenCatch(function(error) { body(); });",
1018                Style);
1019 
1020   verifyFormat("return [aaaaaaaaaaaaaaaaaaaaaa]\n"
1021                "    .aaaaaaa(function() {\n"
1022                "      //\n"
1023                "    })\n"
1024                "    .bbbbbb();");
1025 }
1026 
1027 TEST_F(FormatTestJS, ArrowFunctions) {
1028   verifyFormat("var x = (a) => {\n"
1029                "  return a;\n"
1030                "};");
1031   verifyFormat("var x = (a) => {\n"
1032                "  function y() {\n"
1033                "    return 42;\n"
1034                "  }\n"
1035                "  return a;\n"
1036                "};");
1037   verifyFormat("var x = (a: type): {some: type} => {\n"
1038                "  return a;\n"
1039                "};");
1040   verifyFormat("var x = (a) => a;");
1041   verifyFormat("return () => [];");
1042   verifyFormat("var aaaaaaaaaaaaaaaaaaaa = {\n"
1043                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
1044                "      (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1045                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) =>\n"
1046                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1047                "};");
1048   verifyFormat("var a = a.aaaaaaa(\n"
1049                "    (a: a) => aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) &&\n"
1050                "        aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
1051   verifyFormat("var a = a.aaaaaaa(\n"
1052                "    (a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) ?\n"
1053                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb) :\n"
1054                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
1055 
1056   // FIXME: This is bad, we should be wrapping before "() => {".
1057   verifyFormat("someFunction(() => {\n"
1058                "  doSomething();  // break\n"
1059                "})\n"
1060                "    .doSomethingElse(\n"
1061                "        // break\n"
1062                "    );");
1063   verifyFormat("const f = (x: string|null): string|null => {\n"
1064                "  return x;\n"
1065                "}\n");
1066 }
1067 
1068 TEST_F(FormatTestJS, ReturnStatements) {
1069   verifyFormat("function() {\n"
1070                "  return [hello, world];\n"
1071                "}");
1072 }
1073 
1074 TEST_F(FormatTestJS, ForLoops) {
1075   verifyFormat("for (var i in [2, 3]) {\n"
1076                "}");
1077   verifyFormat("for (var i of [2, 3]) {\n"
1078                "}");
1079   verifyFormat("for (let {a, b} of x) {\n"
1080                "}");
1081   verifyFormat("for (let {a, b} in x) {\n"
1082                "}");
1083 }
1084 
1085 TEST_F(FormatTestJS, WrapRespectsAutomaticSemicolonInsertion) {
1086   // The following statements must not wrap, as otherwise the program meaning
1087   // would change due to automatic semicolon insertion.
1088   // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
1089   verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10));
1090   verifyFormat("return /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10));
1091   verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10));
1092   verifyFormat("continue /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10));
1093   verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10));
1094   verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
1095   verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
1096   verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
1097   verifyFormat("return [\n"
1098                "  aaa\n"
1099                "];",
1100                getGoogleJSStyleWithColumns(12));
1101   verifyFormat("class X {\n"
1102                "  readonly ratherLongField =\n"
1103                "      1;\n"
1104                "}",
1105                "class X {\n"
1106                "  readonly ratherLongField = 1;\n"
1107                "}",
1108                getGoogleJSStyleWithColumns(20));
1109 }
1110 
1111 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
1112   verifyFormat("a\n"
1113                "b;",
1114                " a \n"
1115                " b ;");
1116   verifyFormat("a()\n"
1117                "b;",
1118                " a ()\n"
1119                " b ;");
1120   verifyFormat("a[b]\n"
1121                "c;",
1122                "a [b]\n"
1123                "c ;");
1124   verifyFormat("1\n"
1125                "a;",
1126                "1 \n"
1127                "a ;");
1128   verifyFormat("a\n"
1129                "1;",
1130                "a \n"
1131                "1 ;");
1132   verifyFormat("a\n"
1133                "'x';",
1134                "a \n"
1135                " 'x';");
1136   verifyFormat("a++\n"
1137                "b;",
1138                "a ++\n"
1139                "b ;");
1140   verifyFormat("a\n"
1141                "!b && c;",
1142                "a \n"
1143                " ! b && c;");
1144   verifyFormat("a\n"
1145                "if (1) f();",
1146                " a\n"
1147                " if (1) f();");
1148   verifyFormat("a\n"
1149                "class X {}",
1150                " a\n"
1151                " class X {}");
1152   verifyFormat("var a", "var\n"
1153                         "a");
1154   verifyFormat("x instanceof String", "x\n"
1155                                       "instanceof\n"
1156                                       "String");
1157   verifyFormat("function f(@Foo bar) {}", "function f(@Foo\n"
1158                                           "  bar) {}");
1159   verifyFormat("a = true\n"
1160                "return 1",
1161                "a = true\n"
1162                "  return   1");
1163   verifyFormat("a = 's'\n"
1164                "return 1",
1165                "a = 's'\n"
1166                "  return   1");
1167   verifyFormat("a = null\n"
1168                "return 1",
1169                "a = null\n"
1170                "  return   1");
1171   // Below "class Y {}" should ideally be on its own line.
1172   verifyFormat(
1173       "x = {\n"
1174       "  a: 1\n"
1175       "} class Y {}",
1176       "  x  =  {a  : 1}\n"
1177       "   class  Y {  }");
1178   verifyFormat(
1179       "if (x) {\n"
1180       "}\n"
1181       "return 1",
1182       "if (x) {}\n"
1183       " return   1");
1184   verifyFormat(
1185       "if (x) {\n"
1186       "}\n"
1187       "class X {}",
1188       "if (x) {}\n"
1189       " class X {}");
1190 }
1191 
1192 TEST_F(FormatTestJS, ImportExportASI) {
1193   verifyFormat(
1194       "import {x} from 'y'\n"
1195       "export function z() {}",
1196       "import   {x} from 'y'\n"
1197       "  export function z() {}");
1198   // Below "class Y {}" should ideally be on its own line.
1199   verifyFormat(
1200       "export {x} class Y {}",
1201       "  export {x}\n"
1202       "  class  Y {\n}");
1203   verifyFormat(
1204       "if (x) {\n"
1205       "}\n"
1206       "export class Y {}",
1207       "if ( x ) { }\n"
1208       " export class Y {}");
1209 }
1210 
1211 TEST_F(FormatTestJS, ClosureStyleCasts) {
1212   verifyFormat("var x = /** @type {foo} */ (bar);");
1213 }
1214 
1215 TEST_F(FormatTestJS, TryCatch) {
1216   verifyFormat("try {\n"
1217                "  f();\n"
1218                "} catch (e) {\n"
1219                "  g();\n"
1220                "} finally {\n"
1221                "  h();\n"
1222                "}");
1223 
1224   // But, of course, "catch" is a perfectly fine function name in JavaScript.
1225   verifyFormat("someObject.catch();");
1226   verifyFormat("someObject.new();");
1227   verifyFormat("someObject.delete();");
1228 }
1229 
1230 TEST_F(FormatTestJS, StringLiteralConcatenation) {
1231   verifyFormat("var literal = 'hello ' +\n"
1232                "    'world';");
1233 }
1234 
1235 TEST_F(FormatTestJS, RegexLiteralClassification) {
1236   // Regex literals.
1237   verifyFormat("var regex = /abc/;");
1238   verifyFormat("f(/abc/);");
1239   verifyFormat("f(abc, /abc/);");
1240   verifyFormat("some_map[/abc/];");
1241   verifyFormat("var x = a ? /abc/ : /abc/;");
1242   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
1243   verifyFormat("var x = !/abc/.test(y);");
1244   verifyFormat("var x = foo()! / 10;");
1245   verifyFormat("var x = a && /abc/.test(y);");
1246   verifyFormat("var x = a || /abc/.test(y);");
1247   verifyFormat("var x = a + /abc/.search(y);");
1248   verifyFormat("/abc/.search(y);");
1249   verifyFormat("var regexs = {/abc/, /abc/};");
1250   verifyFormat("return /abc/;");
1251 
1252   // Not regex literals.
1253   verifyFormat("var a = a / 2 + b / 3;");
1254   verifyFormat("var a = a++ / 2;");
1255   // Prefix unary can operate on regex literals, not that it makes sense.
1256   verifyFormat("var a = ++/a/;");
1257 
1258   // This is a known issue, regular expressions are incorrectly detected if
1259   // directly following a closing parenthesis.
1260   verifyFormat("if (foo) / bar /.exec(baz);");
1261 }
1262 
1263 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
1264   verifyFormat("var regex = /=/;");
1265   verifyFormat("var regex = /a*/;");
1266   verifyFormat("var regex = /a+/;");
1267   verifyFormat("var regex = /a?/;");
1268   verifyFormat("var regex = /.a./;");
1269   verifyFormat("var regex = /a\\*/;");
1270   verifyFormat("var regex = /^a$/;");
1271   verifyFormat("var regex = /\\/a/;");
1272   verifyFormat("var regex = /(?:x)/;");
1273   verifyFormat("var regex = /x(?=y)/;");
1274   verifyFormat("var regex = /x(?!y)/;");
1275   verifyFormat("var regex = /x|y/;");
1276   verifyFormat("var regex = /a{2}/;");
1277   verifyFormat("var regex = /a{1,3}/;");
1278 
1279   verifyFormat("var regex = /[abc]/;");
1280   verifyFormat("var regex = /[^abc]/;");
1281   verifyFormat("var regex = /[\\b]/;");
1282   verifyFormat("var regex = /[/]/;");
1283   verifyFormat("var regex = /[\\/]/;");
1284   verifyFormat("var regex = /\\[/;");
1285   verifyFormat("var regex = /\\\\[/]/;");
1286   verifyFormat("var regex = /}[\"]/;");
1287   verifyFormat("var regex = /}[/\"]/;");
1288   verifyFormat("var regex = /}[\"/]/;");
1289 
1290   verifyFormat("var regex = /\\b/;");
1291   verifyFormat("var regex = /\\B/;");
1292   verifyFormat("var regex = /\\d/;");
1293   verifyFormat("var regex = /\\D/;");
1294   verifyFormat("var regex = /\\f/;");
1295   verifyFormat("var regex = /\\n/;");
1296   verifyFormat("var regex = /\\r/;");
1297   verifyFormat("var regex = /\\s/;");
1298   verifyFormat("var regex = /\\S/;");
1299   verifyFormat("var regex = /\\t/;");
1300   verifyFormat("var regex = /\\v/;");
1301   verifyFormat("var regex = /\\w/;");
1302   verifyFormat("var regex = /\\W/;");
1303   verifyFormat("var regex = /a(a)\\1/;");
1304   verifyFormat("var regex = /\\0/;");
1305   verifyFormat("var regex = /\\\\/g;");
1306   verifyFormat("var regex = /\\a\\\\/g;");
1307   verifyFormat("var regex = /\a\\//g;");
1308   verifyFormat("var regex = /a\\//;\n"
1309                "var x = 0;");
1310   verifyFormat("var regex = /'/g;", "var regex = /'/g ;");
1311   verifyFormat("var regex = /'/g;  //'", "var regex = /'/g ; //'");
1312   verifyFormat("var regex = /\\/*/;\n"
1313                "var x = 0;",
1314                "var regex = /\\/*/;\n"
1315                "var x=0;");
1316   verifyFormat("var x = /a\\//;", "var x = /a\\//  \n;");
1317   verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
1318   verifyFormat("var regex =\n"
1319                "    /\"/;",
1320                getGoogleJSStyleWithColumns(15));
1321   verifyFormat("var regex =  //\n"
1322                "    /a/;");
1323   verifyFormat("var regexs = [\n"
1324                "  /d/,   //\n"
1325                "  /aa/,  //\n"
1326                "];");
1327 }
1328 
1329 TEST_F(FormatTestJS, RegexLiteralModifiers) {
1330   verifyFormat("var regex = /abc/g;");
1331   verifyFormat("var regex = /abc/i;");
1332   verifyFormat("var regex = /abc/m;");
1333   verifyFormat("var regex = /abc/y;");
1334 }
1335 
1336 TEST_F(FormatTestJS, RegexLiteralLength) {
1337   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1338                getGoogleJSStyleWithColumns(60));
1339   verifyFormat("var regex =\n"
1340                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1341                getGoogleJSStyleWithColumns(60));
1342   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1343                getGoogleJSStyleWithColumns(50));
1344 }
1345 
1346 TEST_F(FormatTestJS, RegexLiteralExamples) {
1347   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
1348 }
1349 
1350 TEST_F(FormatTestJS, IgnoresMpegTS) {
1351   std::string MpegTS(200, ' ');
1352   MpegTS.replace(0, strlen("nearlyLooks  +   like +   ts + code;  "),
1353                  "nearlyLooks  +   like +   ts + code;  ");
1354   MpegTS[0] = 0x47;
1355   MpegTS[188] = 0x47;
1356   verifyFormat(MpegTS, MpegTS);
1357 }
1358 
1359 TEST_F(FormatTestJS, TypeAnnotations) {
1360   verifyFormat("var x: string;");
1361   verifyFormat("var x: {a: string; b: number;} = {};");
1362   verifyFormat("function x(): string {\n  return 'x';\n}");
1363   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
1364   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
1365   verifyFormat("for (var y: string in x) {\n  x();\n}");
1366   verifyFormat("for (var y: string of x) {\n  x();\n}");
1367   verifyFormat("function x(y: {a?: number;} = {}): number {\n"
1368                "  return 12;\n"
1369                "}");
1370   verifyFormat("((a: string, b: number): string => a + b);");
1371   verifyFormat("var x: (y: number) => string;");
1372   verifyFormat("var x: P<string, (a: number) => string>;");
1373   verifyFormat("var x = {\n"
1374                "  y: function(): z {\n"
1375                "    return 1;\n"
1376                "  }\n"
1377                "};");
1378   verifyFormat("var x = {\n"
1379                "  y: function(): {a: number} {\n"
1380                "    return 1;\n"
1381                "  }\n"
1382                "};");
1383   verifyFormat("function someFunc(args: string[]):\n"
1384                "    {longReturnValue: string[]} {}",
1385                getGoogleJSStyleWithColumns(60));
1386   verifyFormat(
1387       "var someValue = (v as aaaaaaaaaaaaaaaaaaaa<T>[])\n"
1388       "                    .someFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1389 }
1390 
1391 TEST_F(FormatTestJS, UnionIntersectionTypes) {
1392   verifyFormat("let x: A|B = A | B;");
1393   verifyFormat("let x: A&B|C = A & B;");
1394   verifyFormat("let x: Foo<A|B> = new Foo<A|B>();");
1395   verifyFormat("function(x: A|B): C&D {}");
1396   verifyFormat("function(x: A|B = A | B): C&D {}");
1397   verifyFormat("function x(path: number|string) {}");
1398   verifyFormat("function x(): string|number {}");
1399   verifyFormat("type Foo = Bar|Baz;");
1400   verifyFormat("type Foo = Bar<X>|Baz;");
1401   verifyFormat("type Foo = (Bar<X>|Baz);");
1402   verifyFormat("let x: Bar|Baz;");
1403   verifyFormat("let x: Bar<X>|Baz;");
1404   verifyFormat("let x: (Foo|Bar)[];");
1405   verifyFormat("type X = {\n"
1406                "  a: Foo|Bar;\n"
1407                "};");
1408   verifyFormat("export type X = {\n"
1409                "  a: Foo|Bar;\n"
1410                "};");
1411 }
1412 
1413 TEST_F(FormatTestJS, UnionIntersectionTypesInObjectType) {
1414   verifyFormat("let x: {x: number|null} = {x: number | null};");
1415   verifyFormat("let nested: {x: {y: number|null}};");
1416   verifyFormat("let mixed: {x: [number|null, {w: number}]};");
1417   verifyFormat("class X {\n"
1418                "  contructor(x: {\n"
1419                "    a: a|null,\n"
1420                "    b: b|null,\n"
1421                "  }) {}\n"
1422                "}");
1423 }
1424 
1425 TEST_F(FormatTestJS, ClassDeclarations) {
1426   verifyFormat("class C {\n  x: string = 12;\n}");
1427   verifyFormat("class C {\n  x(): string => 12;\n}");
1428   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
1429   verifyFormat("class C {\n"
1430                "  foo() {}\n"
1431                "  [bar]() {}\n"
1432                "}\n");
1433   verifyFormat("class C {\n  private x: string = 12;\n}");
1434   verifyFormat("class C {\n  private static x: string = 12;\n}");
1435   verifyFormat("class C {\n  static x(): string {\n    return 'asd';\n  }\n}");
1436   verifyFormat("class C extends P implements I {}");
1437   verifyFormat("class C extends p.P implements i.I {}");
1438   verifyFormat(
1439       "x(class {\n"
1440       "  a(): A {}\n"
1441       "});");
1442   verifyFormat("class Test {\n"
1443                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
1444                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
1445                "}");
1446   verifyFormat("foo = class Name {\n"
1447                "  constructor() {}\n"
1448                "};");
1449   verifyFormat("foo = class {\n"
1450                "  constructor() {}\n"
1451                "};");
1452   verifyFormat("class C {\n"
1453                "  x: {y: Z;} = {};\n"
1454                "  private y: {y: Z;} = {};\n"
1455                "}");
1456 
1457   // ':' is not a type declaration here.
1458   verifyFormat("class X {\n"
1459                "  subs = {\n"
1460                "    'b': {\n"
1461                "      'c': 1,\n"
1462                "    },\n"
1463                "  };\n"
1464                "}");
1465   verifyFormat("@Component({\n"
1466                "  moduleId: module.id,\n"
1467                "})\n"
1468                "class SessionListComponent implements OnDestroy, OnInit {\n"
1469                "}");
1470 }
1471 
1472 TEST_F(FormatTestJS, InterfaceDeclarations) {
1473   verifyFormat("interface I {\n"
1474                "  x: string;\n"
1475                "  enum: string[];\n"
1476                "  enum?: string[];\n"
1477                "}\n"
1478                "var y;");
1479   // Ensure that state is reset after parsing the interface.
1480   verifyFormat("interface a {}\n"
1481                "export function b() {}\n"
1482                "var x;");
1483 
1484   // Arrays of object type literals.
1485   verifyFormat("interface I {\n"
1486                "  o: {}[];\n"
1487                "}");
1488 }
1489 
1490 TEST_F(FormatTestJS, ObjectTypesInExtendsImplements) {
1491   verifyFormat("class C extends {} {}");
1492   verifyFormat("class C implements {bar: number} {}");
1493   // Somewhat odd, but probably closest to reasonable formatting?
1494   verifyFormat("class C implements {\n"
1495                "  bar: number,\n"
1496                "  baz: string,\n"
1497                "} {}");
1498   verifyFormat("class C<P extends {}> {}");
1499 }
1500 
1501 TEST_F(FormatTestJS, EnumDeclarations) {
1502   verifyFormat("enum Foo {\n"
1503                "  A = 1,\n"
1504                "  B\n"
1505                "}");
1506   verifyFormat("export /* somecomment*/ enum Foo {\n"
1507                "  A = 1,\n"
1508                "  B\n"
1509                "}");
1510   verifyFormat("enum Foo {\n"
1511                "  A = 1,  // comment\n"
1512                "  B\n"
1513                "}\n"
1514                "var x = 1;");
1515   verifyFormat("const enum Foo {\n"
1516                "  A = 1,\n"
1517                "  B\n"
1518                "}");
1519   verifyFormat("export const enum Foo {\n"
1520                "  A = 1,\n"
1521                "  B\n"
1522                "}");
1523 }
1524 
1525 TEST_F(FormatTestJS, MetadataAnnotations) {
1526   verifyFormat("@A\nclass C {\n}");
1527   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
1528   verifyFormat("@A\n@B\nclass C {\n}");
1529   verifyFormat("class C {\n  @A x: string;\n}");
1530   verifyFormat("class C {\n"
1531                "  @A\n"
1532                "  private x(): string {\n"
1533                "    return 'y';\n"
1534                "  }\n"
1535                "}");
1536   verifyFormat("class C {\n"
1537                "  private x(@A x: string) {}\n"
1538                "}");
1539   verifyFormat("class X {}\n"
1540                "class Y {}");
1541   verifyFormat("class X {\n"
1542                "  @property() private isReply = false;\n"
1543                "}\n");
1544 }
1545 
1546 TEST_F(FormatTestJS, TypeAliases) {
1547   verifyFormat("type X = number;\n"
1548                "class C {}");
1549   verifyFormat("type X<Y> = Z<Y>;");
1550   verifyFormat("type X = {\n"
1551                "  y: number\n"
1552                "};\n"
1553                "class C {}");
1554 }
1555 
1556 TEST_F(FormatTestJS, TypeInterfaceLineWrapping) {
1557   const FormatStyle &Style = getGoogleJSStyleWithColumns(20);
1558   verifyFormat("type LongTypeIsReallyUnreasonablyLong =\n"
1559                "    string;\n",
1560                "type LongTypeIsReallyUnreasonablyLong = string;\n",
1561                Style);
1562   verifyFormat(
1563       "interface AbstractStrategyFactoryProvider {\n"
1564       "  a: number\n"
1565       "}\n",
1566       "interface AbstractStrategyFactoryProvider { a: number }\n",
1567       Style);
1568 }
1569 
1570 TEST_F(FormatTestJS, Modules) {
1571   verifyFormat("import SomeThing from 'some/module.js';");
1572   verifyFormat("import {X, Y} from 'some/module.js';");
1573   verifyFormat("import a, {X, Y} from 'some/module.js';");
1574   verifyFormat("import {X, Y,} from 'some/module.js';");
1575   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
1576   // Ensure Automatic Semicolon Insertion does not break on "as\n".
1577   verifyFormat("import {X as myX} from 'm';", "import {X as\n"
1578                                               " myX} from 'm';");
1579   verifyFormat("import * as lib from 'some/module.js';");
1580   verifyFormat("var x = {import: 1};\nx.import = 2;");
1581 
1582   verifyFormat("export function fn() {\n"
1583                "  return 'fn';\n"
1584                "}");
1585   verifyFormat("export function A() {}\n"
1586                "export default function B() {}\n"
1587                "export function C() {}");
1588   verifyFormat("export default () => {\n"
1589                "  let x = 1;\n"
1590                "  return x;\n"
1591                "}");
1592   verifyFormat("export const x = 12;");
1593   verifyFormat("export default class X {}");
1594   verifyFormat("export {X, Y} from 'some/module.js';");
1595   verifyFormat("export {X, Y,} from 'some/module.js';");
1596   verifyFormat("export {SomeVeryLongExport as X, "
1597                "SomeOtherVeryLongExport as Y} from 'some/module.js';");
1598   // export without 'from' is wrapped.
1599   verifyFormat("export let someRatherLongVariableName =\n"
1600                "    someSurprisinglyLongVariable + someOtherRatherLongVar;");
1601   // ... but not if from is just an identifier.
1602   verifyFormat("export {\n"
1603                "  from as from,\n"
1604                "  someSurprisinglyLongVariable as\n"
1605                "      from\n"
1606                "};",
1607                getGoogleJSStyleWithColumns(20));
1608   verifyFormat("export class C {\n"
1609                "  x: number;\n"
1610                "  y: string;\n"
1611                "}");
1612   verifyFormat("export class X { y: number; }");
1613   verifyFormat("export abstract class X { y: number; }");
1614   verifyFormat("export default class X { y: number }");
1615   verifyFormat("export default function() {\n  return 1;\n}");
1616   verifyFormat("export var x = 12;");
1617   verifyFormat("class C {}\n"
1618                "export function f() {}\n"
1619                "var v;");
1620   verifyFormat("export var x: number = 12;");
1621   verifyFormat("export const y = {\n"
1622                "  a: 1,\n"
1623                "  b: 2\n"
1624                "};");
1625   verifyFormat("export enum Foo {\n"
1626                "  BAR,\n"
1627                "  // adsdasd\n"
1628                "  BAZ\n"
1629                "}");
1630   verifyFormat("export default [\n"
1631                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1632                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
1633                "];");
1634   verifyFormat("export default [];");
1635   verifyFormat("export default () => {};");
1636   verifyFormat("export interface Foo { foo: number; }\n"
1637                "export class Bar {\n"
1638                "  blah(): string {\n"
1639                "    return this.blah;\n"
1640                "  };\n"
1641                "}");
1642 }
1643 
1644 TEST_F(FormatTestJS, ImportWrapping) {
1645   verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
1646                " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
1647                "} from 'some/module.js';");
1648   FormatStyle Style = getGoogleJSStyleWithColumns(80);
1649   Style.JavaScriptWrapImports = true;
1650   verifyFormat("import {\n"
1651                "  VeryLongImportsAreAnnoying,\n"
1652                "  VeryLongImportsAreAnnoying,\n"
1653                "  VeryLongImportsAreAnnoying,\n"
1654                "} from 'some/module.js';",
1655                Style);
1656   verifyFormat("import {\n"
1657                "  A,\n"
1658                "  A,\n"
1659                "} from 'some/module.js';",
1660                Style);
1661   verifyFormat("export {\n"
1662                "  A,\n"
1663                "  A,\n"
1664                "} from 'some/module.js';",
1665                Style);
1666   Style.ColumnLimit = 40;
1667   // Using this version of verifyFormat because test::messUp hides the issue.
1668   verifyFormat("import {\n"
1669                "  A,\n"
1670                "} from\n"
1671                "    'some/path/longer/than/column/limit/module.js';",
1672                " import  {  \n"
1673                "    A,  \n"
1674                "  }    from\n"
1675                "      'some/path/longer/than/column/limit/module.js'  ; ",
1676                Style);
1677 }
1678 
1679 TEST_F(FormatTestJS, TemplateStrings) {
1680   // Keeps any whitespace/indentation within the template string.
1681   verifyFormat("var x = `hello\n"
1682             "     ${name}\n"
1683             "  !`;",
1684             "var x    =    `hello\n"
1685                    "     ${  name    }\n"
1686                    "  !`;");
1687 
1688   verifyFormat("var x =\n"
1689                "    `hello ${world}` >= some();",
1690                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
1691   verifyFormat("var x = `hello ${world}` >= some();",
1692                getGoogleJSStyleWithColumns(35)); // Barely fits.
1693   verifyFormat("var x = `hellö ${wörld}` >= söme();",
1694                getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8.
1695   verifyFormat("var x = `hello\n"
1696             "  ${world}` >=\n"
1697             "    some();",
1698             "var x =\n"
1699                    "    `hello\n"
1700                    "  ${world}` >= some();",
1701                    getGoogleJSStyleWithColumns(21)); // Barely doesn't fit.
1702   verifyFormat("var x = `hello\n"
1703             "  ${world}` >= some();",
1704             "var x =\n"
1705                    "    `hello\n"
1706                    "  ${world}` >= some();",
1707                    getGoogleJSStyleWithColumns(22)); // Barely fits.
1708 
1709   verifyFormat("var x =\n"
1710                "    `h`;",
1711                getGoogleJSStyleWithColumns(11));
1712   verifyFormat("var x =\n    `multi\n  line`;", "var x = `multi\n  line`;",
1713                getGoogleJSStyleWithColumns(13));
1714   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1715                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
1716   // Repro for an obscure width-miscounting issue with template strings.
1717   verifyFormat(
1718       "someLongVariable =\n"
1719       "    "
1720       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;",
1721       "someLongVariable = "
1722       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;");
1723 
1724   // Make sure template strings get a proper ColumnWidth assigned, even if they
1725   // are first token in line.
1726   verifyFormat(
1727       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1728       "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
1729 
1730   // Two template strings.
1731   verifyFormat("var x = `hello` == `hello`;");
1732 
1733   // Comments in template strings.
1734   verifyFormat("var x = `//a`;\n"
1735             "var y;",
1736             "var x =\n `//a`;\n"
1737                    "var y  ;");
1738   verifyFormat("var x = `/*a`;\n"
1739                "var y;",
1740                "var x =\n `/*a`;\n"
1741                "var y;");
1742   // Unterminated string literals in a template string.
1743   verifyFormat("var x = `'`;  // comment with matching quote '\n"
1744                "var y;");
1745   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
1746                "var y;");
1747   verifyFormat("it(`'aaaaaaaaaaaaaaa   `, aaaaaaaaa);",
1748                "it(`'aaaaaaaaaaaaaaa   `,   aaaaaaaaa) ;",
1749                getGoogleJSStyleWithColumns(40));
1750   // Backticks in a comment - not a template string.
1751   verifyFormat("var x = 1  // `/*a`;\n"
1752                "    ;",
1753                "var x =\n 1  // `/*a`;\n"
1754                "    ;");
1755   verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */");
1756   // Comment spans multiple template strings.
1757   verifyFormat("var x = `/*a`;\n"
1758                "var y = ` */ `;",
1759                "var x =\n `/*a`;\n"
1760                "var y =\n ` */ `;");
1761   // Escaped backtick.
1762   verifyFormat("var x = ` \\` a`;\n"
1763                "var y;",
1764                "var x = ` \\` a`;\n"
1765                "var y;");
1766   // Escaped dollar.
1767   verifyFormat("var x = ` \\${foo}`;\n");
1768 
1769   // The token stream can contain two string_literals in sequence, but that
1770   // doesn't mean that they are implicitly concatenated in JavaScript.
1771   verifyFormat("var f = `aaaa ${a ? 'a' : 'b'}`;");
1772 
1773   // Ensure that scopes are appropriately set around evaluated expressions in
1774   // template strings.
1775   verifyFormat("var f = `aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa\n"
1776                "         aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`;",
1777                "var f = `aaaaaaaaaaaaa:${aaaaaaa.  aaaaa} aaaaaaaa\n"
1778                "         aaaaaaaaaaaaa:${  aaaaaaa. aaaaa} aaaaaaaa`;");
1779   verifyFormat("var x = someFunction(`${})`)  //\n"
1780                "            .oooooooooooooooooon();");
1781   verifyFormat("var x = someFunction(`${aaaa}${\n"
1782                "                               aaaaa(  //\n"
1783                "                                   aaaaa)\n"
1784                "                             })`);");
1785 }
1786 
1787 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) {
1788   verifyFormat("var f = `aaaaaaaaaaaaaaaaaa: ${\n"
1789                "                               aaaaa +  //\n"
1790                "                               bbbb\n"
1791                "                             }`;",
1792                "var f = `aaaaaaaaaaaaaaaaaa: ${aaaaa +  //\n"
1793                "                               bbbb}`;");
1794   verifyFormat("var f = `\n"
1795                "  aaaaaaaaaaaaaaaaaa: ${\n"
1796                "                        aaaaa +  //\n"
1797                "                        bbbb\n"
1798                "                      }`;",
1799                "var f  =  `\n"
1800                "  aaaaaaaaaaaaaaaaaa: ${   aaaaa  +  //\n"
1801                "                        bbbb }`;");
1802   verifyFormat("var f = `\n"
1803                "  aaaaaaaaaaaaaaaaaa: ${\n"
1804                "                        someFunction(\n"
1805                "                            aaaaa +  //\n"
1806                "                            bbbb)\n"
1807                "                      }`;",
1808                "var f  =  `\n"
1809                "  aaaaaaaaaaaaaaaaaa: ${someFunction (\n"
1810                "                            aaaaa  +   //\n"
1811                "                            bbbb)}`;");
1812 
1813   // It might be preferable to wrap before "someFunction".
1814   verifyFormat("var f = `\n"
1815                "  aaaaaaaaaaaaaaaaaa: ${someFunction({\n"
1816                "                          aaaa: aaaaa,\n"
1817                "                          bbbb: bbbbb,\n"
1818                "                        })}`;",
1819                "var f  =  `\n"
1820                "  aaaaaaaaaaaaaaaaaa: ${someFunction ({\n"
1821                "                          aaaa:  aaaaa,\n"
1822                "                          bbbb:  bbbbb,\n"
1823                "                        })}`;");
1824 }
1825 
1826 TEST_F(FormatTestJS, TemplateStringASI) {
1827   verifyFormat("var x = `hello${world}`;", "var x = `hello${\n"
1828                                            "    world\n"
1829                                            "}`;");
1830 }
1831 
1832 TEST_F(FormatTestJS, NestedTemplateStrings) {
1833   verifyFormat(
1834       "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;");
1835   verifyFormat("var x = `he${({text: 'll'}.text)}o`;");
1836 
1837   // Crashed at some point.
1838   verifyFormat("}");
1839 }
1840 
1841 TEST_F(FormatTestJS, TaggedTemplateStrings) {
1842   verifyFormat("var x = html`<ul>`;");
1843   verifyFormat("yield `hello`;");
1844 }
1845 
1846 TEST_F(FormatTestJS, CastSyntax) {
1847   verifyFormat("var x = <type>foo;");
1848   verifyFormat("var x = foo as type;");
1849   verifyFormat("let x = (a + b) as\n"
1850                "    LongTypeIsLong;",
1851                getGoogleJSStyleWithColumns(20));
1852   verifyFormat("foo = <Bar[]>[\n"
1853                "  1,  //\n"
1854                "  2\n"
1855                "];");
1856   verifyFormat("var x = [{x: 1} as type];");
1857   verifyFormat("x = x as [a, b];");
1858   verifyFormat("x = x as {a: string};");
1859   verifyFormat("x = x as (string);");
1860   verifyFormat("x = x! as (string);");
1861   verifyFormat("var x = something.someFunction() as\n"
1862                "    something;",
1863                getGoogleJSStyleWithColumns(40));
1864 }
1865 
1866 TEST_F(FormatTestJS, TypeArguments) {
1867   verifyFormat("class X<Y> {}");
1868   verifyFormat("new X<Y>();");
1869   verifyFormat("foo<Y>(a);");
1870   verifyFormat("var x: X<Y>[];");
1871   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
1872   verifyFormat("function f(a: List<any> = null) {}");
1873   verifyFormat("function f(): List<any> {}");
1874   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
1875                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
1876   verifyFormat("function aaaaaaaaaa(\n"
1877                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
1878                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
1879                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
1880 }
1881 
1882 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
1883   verifyFormat(
1884       "function foo(check: Object):\n"
1885       "    check is {foo: string, bar: string, baz: string, foobar: string} {\n"
1886       "  return 'bar' in check;\n"
1887       "}\n");
1888 }
1889 
1890 TEST_F(FormatTestJS, OptionalTypes) {
1891   verifyFormat("function x(a?: b, c?, d?) {}");
1892   verifyFormat("class X {\n"
1893                "  y?: z;\n"
1894                "  z?;\n"
1895                "}");
1896   verifyFormat("interface X {\n"
1897                "  y?(): z;\n"
1898                "}");
1899   verifyFormat("constructor({aa}: {\n"
1900                "  aa?: string,\n"
1901                "  aaaaaaaa?: string,\n"
1902                "  aaaaaaaaaaaaaaa?: boolean,\n"
1903                "  aaaaaa?: List<string>\n"
1904                "}) {}");
1905 }
1906 
1907 TEST_F(FormatTestJS, IndexSignature) {
1908   verifyFormat("var x: {[k: string]: v};");
1909 }
1910 
1911 TEST_F(FormatTestJS, WrapAfterParen) {
1912   verifyFormat("xxxxxxxxxxx(\n"
1913                "    aaa, aaa);",
1914                getGoogleJSStyleWithColumns(20));
1915   verifyFormat("xxxxxxxxxxx(\n"
1916                "    aaa, aaa, aaa,\n"
1917                "    aaa, aaa, aaa);",
1918                getGoogleJSStyleWithColumns(20));
1919   verifyFormat("xxxxxxxxxxx(\n"
1920                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
1921                "    function(x) {\n"
1922                "      y();  //\n"
1923                "    });",
1924                getGoogleJSStyleWithColumns(40));
1925   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
1926                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
1927 }
1928 
1929 TEST_F(FormatTestJS, JSDocAnnotations) {
1930   verifyFormat("/**\n"
1931                " * @export {this.is.a.long.path.to.a.Type}\n"
1932                " */",
1933                "/**\n"
1934                " * @export {this.is.a.long.path.to.a.Type}\n"
1935                " */",
1936                getGoogleJSStyleWithColumns(20));
1937   verifyFormat("/**\n"
1938                " * @mods {this.is.a.long.path.to.a.Type}\n"
1939                " */",
1940                "/**\n"
1941                " * @mods {this.is.a.long.path.to.a.Type}\n"
1942                " */",
1943                getGoogleJSStyleWithColumns(20));
1944   verifyFormat("/**\n"
1945                " * @param {this.is.a.long.path.to.a.Type}\n"
1946                " */",
1947                "/**\n"
1948                " * @param {this.is.a.long.path.to.a.Type}\n"
1949                " */",
1950                getGoogleJSStyleWithColumns(20));
1951   verifyFormat("/**\n"
1952                " * @see http://very/very/long/url/is/long\n"
1953                " */",
1954                "/**\n"
1955                " * @see http://very/very/long/url/is/long\n"
1956                " */",
1957                getGoogleJSStyleWithColumns(20));
1958   verifyFormat(
1959       "/**\n"
1960       " * @param This is a\n"
1961       " * long comment but\n"
1962       " * no type\n"
1963       " */",
1964       "/**\n"
1965       " * @param This is a long comment but no type\n"
1966       " */",
1967       getGoogleJSStyleWithColumns(20));
1968   // Don't break @param line, but reindent it and reflow unrelated lines.
1969   verifyFormat("{\n"
1970                "  /**\n"
1971                "   * long long long\n"
1972                "   * long\n"
1973                "   * @param {this.is.a.long.path.to.a.Type} a\n"
1974                "   * long long long\n"
1975                "   * long long\n"
1976                "   */\n"
1977                "  function f(a) {}\n"
1978                "}",
1979                "{\n"
1980                "/**\n"
1981                " * long long long long\n"
1982                " * @param {this.is.a.long.path.to.a.Type} a\n"
1983                " * long long long long\n"
1984                " * long\n"
1985                " */\n"
1986                "  function f(a) {}\n"
1987                "}",
1988                getGoogleJSStyleWithColumns(20));
1989 }
1990 
1991 TEST_F(FormatTestJS, RequoteStringsSingle) {
1992   verifyFormat("var x = 'foo';", "var x = \"foo\";");
1993   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";");
1994   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";");
1995   verifyFormat(
1996       "var x =\n"
1997       "    'foo\\'';",
1998       // Code below is 15 chars wide, doesn't fit into the line with the
1999       // \ escape added.
2000       "var x = \"foo'\";", getGoogleJSStyleWithColumns(15));
2001   // Removes no-longer needed \ escape from ".
2002   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";");
2003   // Code below fits into 15 chars *after* removing the \ escape.
2004   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";",
2005                getGoogleJSStyleWithColumns(15));
2006   verifyFormat("// clang-format off\n"
2007                "let x = \"double\";\n"
2008                "// clang-format on\n"
2009                "let x = 'single';\n",
2010                "// clang-format off\n"
2011                "let x = \"double\";\n"
2012                "// clang-format on\n"
2013                "let x = \"single\";\n");
2014 }
2015 
2016 TEST_F(FormatTestJS, RequoteAndIndent) {
2017   verifyFormat("let x = someVeryLongFunctionThatGoesOnAndOn(\n"
2018                "    'double quoted string that needs wrapping');",
2019                "let x = someVeryLongFunctionThatGoesOnAndOn("
2020                "\"double quoted string that needs wrapping\");");
2021 
2022   verifyFormat("let x =\n"
2023                "    'foo\\'oo';\n"
2024                "let x =\n"
2025                "    'foo\\'oo';",
2026                "let x=\"foo'oo\";\n"
2027                "let x=\"foo'oo\";",
2028                getGoogleJSStyleWithColumns(15));
2029 }
2030 
2031 TEST_F(FormatTestJS, RequoteStringsDouble) {
2032   FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2033   DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double;
2034   verifyFormat("var x = \"foo\";", DoubleQuotes);
2035   verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes);
2036   verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes);
2037 }
2038 
2039 TEST_F(FormatTestJS, RequoteStringsLeave) {
2040   FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2041   LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave;
2042   verifyFormat("var x = \"foo\";", LeaveQuotes);
2043   verifyFormat("var x = 'foo';", LeaveQuotes);
2044 }
2045 
2046 TEST_F(FormatTestJS, SupportShebangLines) {
2047   verifyFormat("#!/usr/bin/env node\n"
2048                "var x = hello();",
2049                "#!/usr/bin/env node\n"
2050                "var x   =  hello();");
2051 }
2052 
2053 TEST_F(FormatTestJS, NonNullAssertionOperator) {
2054   verifyFormat("let x = foo!.bar();\n");
2055   verifyFormat("let x = foo ? bar! : baz;\n");
2056   verifyFormat("let x = !foo;\n");
2057   verifyFormat("let x = foo[0]!;\n");
2058   verifyFormat("let x = (foo)!;\n");
2059   verifyFormat("let x = x(foo!);\n");
2060   verifyFormat(
2061       "a.aaaaaa(a.a!).then(\n"
2062       "    x => x(x));\n",
2063       getGoogleJSStyleWithColumns(20));
2064   verifyFormat("let x = foo! - 1;\n");
2065   verifyFormat("let x = {foo: 1}!;\n");
2066   verifyFormat(
2067       "let x = hello.foo()!\n"
2068       "            .foo()!\n"
2069       "            .foo()!\n"
2070       "            .foo()!;\n",
2071       getGoogleJSStyleWithColumns(20));
2072   verifyFormat("let x = namespace!;\n");
2073   verifyFormat("return !!x;\n");
2074 }
2075 
2076 TEST_F(FormatTestJS, Conditional) {
2077   verifyFormat("y = x ? 1 : 2;");
2078   verifyFormat("x ? 1 : 2;");
2079   verifyFormat("class Foo {\n"
2080                "  field = true ? 1 : 2;\n"
2081                "  method(a = true ? 1 : 2) {}\n"
2082                "}");
2083 }
2084 
2085 TEST_F(FormatTestJS, ImportComments) {
2086   verifyFormat("import {x} from 'x';  // from some location",
2087                getGoogleJSStyleWithColumns(25));
2088   verifyFormat("// taze: x from 'location'", getGoogleJSStyleWithColumns(10));
2089   verifyFormat("/// <reference path=\"some/location\" />", getGoogleJSStyleWithColumns(10));
2090 }
2091 
2092 TEST_F(FormatTestJS, Exponentiation) {
2093   verifyFormat("squared = x ** 2;");
2094   verifyFormat("squared **= 2;");
2095 }
2096 
2097 TEST_F(FormatTestJS, NestedLiterals) {
2098   FormatStyle FourSpaces = getGoogleJSStyleWithColumns(15);
2099   FourSpaces.IndentWidth = 4;
2100   verifyFormat("var l = [\n"
2101                "    [\n"
2102                "        1,\n"
2103                "    ],\n"
2104                "];", FourSpaces);
2105   verifyFormat("var l = [\n"
2106                "    {\n"
2107                "        1: 1,\n"
2108                "    },\n"
2109                "];", FourSpaces);
2110   verifyFormat("someFunction(\n"
2111                "    p1,\n"
2112                "    [\n"
2113                "        1,\n"
2114                "    ],\n"
2115                ");", FourSpaces);
2116   verifyFormat("someFunction(\n"
2117                "    p1,\n"
2118                "    {\n"
2119                "        1: 1,\n"
2120                "    },\n"
2121                ");", FourSpaces);
2122   verifyFormat("var o = {\n"
2123                "    1: 1,\n"
2124                "    2: {\n"
2125                "        3: 3,\n"
2126                "    },\n"
2127                "};", FourSpaces);
2128   verifyFormat("var o = {\n"
2129                "    1: 1,\n"
2130                "    2: [\n"
2131                "        3,\n"
2132                "    ],\n"
2133                "};", FourSpaces);
2134 }
2135 
2136 TEST_F(FormatTestJS, BackslashesInComments) {
2137   verifyFormat("// hello \\\n"
2138                "if (x) foo();\n",
2139                "// hello \\\n"
2140                "     if ( x) \n"
2141                "   foo();\n");
2142   verifyFormat("/* ignore \\\n"
2143                " */\n"
2144                "if (x) foo();\n",
2145                "/* ignore \\\n"
2146                " */\n"
2147                " if (  x) foo();\n");
2148   verifyFormat("// st \\ art\\\n"
2149                "// comment"
2150                "// continue \\\n"
2151                "formatMe();\n",
2152                "// st \\ art\\\n"
2153                "// comment"
2154                "// continue \\\n"
2155                "formatMe( );\n");
2156 }
2157 
2158 } // end namespace tooling
2159 } // end namespace clang
2160