xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision befb9dc3694e95355f21650de7acb058ac89f993)
1 //===- unittest/Format/FormatTestJS.cpp - Formatting unit tests for JS ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "FormatTestUtils.h"
10 #include "clang/Format/Format.h"
11 #include "llvm/Support/Debug.h"
12 #include "gtest/gtest.h"
13 
14 #define DEBUG_TYPE "format-test"
15 
16 namespace clang {
17 namespace format {
18 
19 class FormatTestJS : public ::testing::Test {
20 protected:
21   static std::string format(llvm::StringRef Code, unsigned Offset,
22                             unsigned Length, const FormatStyle &Style) {
23     LLVM_DEBUG(llvm::errs() << "---\n");
24     LLVM_DEBUG(llvm::errs() << Code << "\n\n");
25     std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
26     FormattingAttemptStatus Status;
27     tooling::Replacements Replaces =
28         reformat(Style, Code, Ranges, "<stdin>", &Status);
29     EXPECT_TRUE(Status.FormatComplete);
30     auto Result = applyAllReplacements(Code, Replaces);
31     EXPECT_TRUE(static_cast<bool>(Result));
32     LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
33     return *Result;
34   }
35 
36   static std::string format(
37       llvm::StringRef Code,
38       const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
39     return format(Code, 0, Code.size(), Style);
40   }
41 
42   static FormatStyle getGoogleJSStyleWithColumns(unsigned ColumnLimit) {
43     FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
44     Style.ColumnLimit = ColumnLimit;
45     return Style;
46   }
47 
48   static void verifyFormat(
49       llvm::StringRef Code,
50       const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
51     EXPECT_EQ(Code.str(), format(Code, Style)) << "Expected code is not stable";
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, llvm::StringRef Code,
58       const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
59     EXPECT_EQ(Expected.str(), format(Expected, Style))
60         << "Expected code is not stable";
61     std::string Result = format(Code, Style);
62     EXPECT_EQ(Expected.str(), Result) << "Formatted:\n" << Result;
63   }
64 };
65 
66 TEST_F(FormatTestJS, BlockComments) {
67   verifyFormat("/* aaaaaaaaaaaaa */ aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
68                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
69   // Breaks after a single line block comment.
70   EXPECT_EQ("aaaaa = bbbb.ccccccccccccccc(\n"
71             "    /** @type_{!cccc.rrrrrrr.MMMMMMMMMMMM.LLLLLLLLLLL.lala} */\n"
72             "    mediaMessage);",
73             format("aaaaa = bbbb.ccccccccccccccc(\n"
74                    "    /** "
75                    "@type_{!cccc.rrrrrrr.MMMMMMMMMMMM.LLLLLLLLLLL.lala} */ "
76                    "mediaMessage);",
77                    getGoogleJSStyleWithColumns(70)));
78   // Breaks after a multiline block comment.
79   EXPECT_EQ(
80       "aaaaa = bbbb.ccccccccccccccc(\n"
81       "    /**\n"
82       "     * @type_{!cccc.rrrrrrr.MMMMMMMMMMMM.LLLLLLLLLLL.lala}\n"
83       "     */\n"
84       "    mediaMessage);",
85       format("aaaaa = bbbb.ccccccccccccccc(\n"
86              "    /**\n"
87              "     * @type_{!cccc.rrrrrrr.MMMMMMMMMMMM.LLLLLLLLLLL.lala}\n"
88              "     */ mediaMessage);",
89              getGoogleJSStyleWithColumns(70)));
90 }
91 
92 TEST_F(FormatTestJS, JSDocComments) {
93   // Break the first line of a multiline jsdoc comment.
94   EXPECT_EQ("/**\n"
95             " * jsdoc line 1\n"
96             " * jsdoc line 2\n"
97             " */",
98             format("/** jsdoc line 1\n"
99                    " * jsdoc line 2\n"
100                    " */",
101                    getGoogleJSStyleWithColumns(20)));
102   // Both break after '/**' and break the line itself.
103   EXPECT_EQ("/**\n"
104             " * jsdoc line long\n"
105             " * long jsdoc line 2\n"
106             " */",
107             format("/** jsdoc line long long\n"
108                    " * jsdoc line 2\n"
109                    " */",
110                    getGoogleJSStyleWithColumns(20)));
111   // Break a short first line if the ending '*/' is on a newline.
112   EXPECT_EQ("/**\n"
113             " * jsdoc line 1\n"
114             " */",
115             format("/** jsdoc line 1\n"
116                    " */",
117                    getGoogleJSStyleWithColumns(20)));
118   // Don't break the first line of a short single line jsdoc comment.
119   EXPECT_EQ("/** jsdoc line 1 */",
120             format("/** jsdoc line 1 */", getGoogleJSStyleWithColumns(20)));
121   // Don't break the first line of a single line jsdoc comment if it just fits
122   // the column limit.
123   EXPECT_EQ("/** jsdoc line 12 */",
124             format("/** jsdoc line 12 */", getGoogleJSStyleWithColumns(20)));
125   // Don't break after '/**' and before '*/' if there is no space between
126   // '/**' and the content.
127   EXPECT_EQ(
128       "/*** nonjsdoc long\n"
129       " * line */",
130       format("/*** nonjsdoc long line */", getGoogleJSStyleWithColumns(20)));
131   EXPECT_EQ(
132       "/**strange long long\n"
133       " * line */",
134       format("/**strange long long line */", getGoogleJSStyleWithColumns(20)));
135   // Break the first line of a single line jsdoc comment if it just exceeds the
136   // column limit.
137   EXPECT_EQ("/**\n"
138             " * jsdoc line 123\n"
139             " */",
140             format("/** jsdoc line 123 */", getGoogleJSStyleWithColumns(20)));
141   // Break also if the leading indent of the first line is more than 1 column.
142   EXPECT_EQ("/**\n"
143             " * jsdoc line 123\n"
144             " */",
145             format("/**  jsdoc line 123 */", getGoogleJSStyleWithColumns(20)));
146   // Break also if the leading indent of the first line is more than 1 column.
147   EXPECT_EQ("/**\n"
148             " * jsdoc line 123\n"
149             " */",
150             format("/**   jsdoc line 123 */", getGoogleJSStyleWithColumns(20)));
151   // Break after the content of the last line.
152   EXPECT_EQ("/**\n"
153             " * line 1\n"
154             " * line 2\n"
155             " */",
156             format("/**\n"
157                    " * line 1\n"
158                    " * line 2 */",
159                    getGoogleJSStyleWithColumns(20)));
160   // Break both the content and after the content of the last line.
161   EXPECT_EQ("/**\n"
162             " * line 1\n"
163             " * line long long\n"
164             " * long\n"
165             " */",
166             format("/**\n"
167                    " * line 1\n"
168                    " * line long long long */",
169                    getGoogleJSStyleWithColumns(20)));
170 
171   // The comment block gets indented.
172   EXPECT_EQ("function f() {\n"
173             "  /**\n"
174             "   * comment about\n"
175             "   * x\n"
176             "   */\n"
177             "  var x = 1;\n"
178             "}",
179             format("function f() {\n"
180                    "/** comment about x */\n"
181                    "var x = 1;\n"
182                    "}",
183                    getGoogleJSStyleWithColumns(20)));
184 
185   // Don't break the first line of a single line short jsdoc comment pragma.
186   EXPECT_EQ("/** @returns j */",
187             format("/** @returns j */", getGoogleJSStyleWithColumns(20)));
188 
189   // Break a single line long jsdoc comment pragma.
190   EXPECT_EQ("/**\n"
191             " * @returns {string}\n"
192             " *     jsdoc line 12\n"
193             " */",
194             format("/** @returns {string} jsdoc line 12 */",
195                    getGoogleJSStyleWithColumns(20)));
196 
197   // FIXME: this overcounts the */ as a continuation of the 12 when breaking.
198   // Related to the FIXME in BreakableBlockComment::getRangeLength.
199   EXPECT_EQ("/**\n"
200             " * @returns {string}\n"
201             " *     jsdoc line line\n"
202             " *     12\n"
203             " */",
204             format("/** @returns {string} jsdoc line line 12*/",
205                    getGoogleJSStyleWithColumns(25)));
206 
207   // Fix a multiline jsdoc comment ending in a comment pragma.
208   EXPECT_EQ("/**\n"
209             " * line 1\n"
210             " * line 2\n"
211             " * @returns {string}\n"
212             " *     jsdoc line 12\n"
213             " */",
214             format("/** line 1\n"
215                    " * line 2\n"
216                    " * @returns {string} jsdoc line 12 */",
217                    getGoogleJSStyleWithColumns(20)));
218 
219   EXPECT_EQ("/**\n"
220             " * line 1\n"
221             " * line 2\n"
222             " *\n"
223             " * @returns j\n"
224             " */",
225             format("/** line 1\n"
226                    " * line 2\n"
227                    " *\n"
228                    " * @returns j */",
229                    getGoogleJSStyleWithColumns(20)));
230 }
231 
232 TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
233   verifyFormat("a == = b;");
234   verifyFormat("a != = b;");
235 
236   verifyFormat("a === b;");
237   verifyFormat("aaaaaaa ===\n    b;", getGoogleJSStyleWithColumns(10));
238   verifyFormat("a !== b;");
239   verifyFormat("aaaaaaa !==\n    b;", getGoogleJSStyleWithColumns(10));
240   verifyFormat("if (a + b + c +\n"
241                "        d !==\n"
242                "    e + f + g)\n"
243                "  q();",
244                getGoogleJSStyleWithColumns(20));
245 
246   verifyFormat("a >> >= b;");
247 
248   verifyFormat("a >>> b;");
249   verifyFormat("aaaaaaa >>>\n    b;", getGoogleJSStyleWithColumns(10));
250   verifyFormat("a >>>= b;");
251   verifyFormat("aaaaaaa >>>=\n    b;", getGoogleJSStyleWithColumns(10));
252   verifyFormat("if (a + b + c +\n"
253                "        d >>>\n"
254                "    e + f + g)\n"
255                "  q();",
256                getGoogleJSStyleWithColumns(20));
257   verifyFormat("var x = aaaaaaaaaa ?\n"
258                "    bbbbbb :\n"
259                "    ccc;",
260                getGoogleJSStyleWithColumns(20));
261 
262   verifyFormat("var b = a.map((x) => x + 1);");
263   verifyFormat("return ('aaa') in bbbb;");
264   verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
265                "    aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
266   FormatStyle Style = getGoogleJSStyleWithColumns(80);
267   Style.AlignOperands = FormatStyle::OAS_Align;
268   verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
269                "        aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
270                Style);
271   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
272   verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa()\n"
273                "            in aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
274                Style);
275 
276   // ES6 spread operator.
277   verifyFormat("someFunction(...a);");
278   verifyFormat("var x = [1, ...a, 2];");
279 
280   // "- -1" is legal JS syntax, but must not collapse into "--".
281   verifyFormat("- -1;", " - -1;");
282   verifyFormat("-- -1;", " -- -1;");
283   verifyFormat("+ +1;", " + +1;");
284   verifyFormat("++ +1;", " ++ +1;");
285 }
286 
287 TEST_F(FormatTestJS, UnderstandsAmpAmp) {
288   verifyFormat("e && e.SomeFunction();");
289 }
290 
291 TEST_F(FormatTestJS, LiteralOperatorsCanBeKeywords) {
292   verifyFormat("not.and.or.not_eq = 1;");
293 }
294 
295 TEST_F(FormatTestJS, ReservedWords) {
296   // JavaScript reserved words (aka keywords) are only illegal when used as
297   // Identifiers, but are legal as IdentifierNames.
298   verifyFormat("x.class.struct = 1;");
299   verifyFormat("x.case = 1;");
300   verifyFormat("x.interface = 1;");
301   verifyFormat("x.for = 1;");
302   verifyFormat("x.of();");
303   verifyFormat("of(null);");
304   verifyFormat("return of(null);");
305   verifyFormat("import {of} from 'x';");
306   verifyFormat("x.in();");
307   verifyFormat("x.let();");
308   verifyFormat("x.var();");
309   verifyFormat("x.for();");
310   verifyFormat("x.as();");
311   verifyFormat("x.instanceof();");
312   verifyFormat("x.switch();");
313   verifyFormat("x.case();");
314   verifyFormat("x.delete();");
315   verifyFormat("x.throw();");
316   verifyFormat("x.throws();");
317   verifyFormat("x.if();");
318   verifyFormat("x = {\n"
319                "  a: 12,\n"
320                "  interface: 1,\n"
321                "  switch: 1,\n"
322                "};");
323   verifyFormat("var struct = 2;");
324   verifyFormat("var union = 2;");
325   verifyFormat("var interface = 2;");
326   verifyFormat("interface = 2;");
327   verifyFormat("x = interface instanceof y;");
328   verifyFormat("interface Test {\n"
329                "  x: string;\n"
330                "  switch: string;\n"
331                "  case: string;\n"
332                "  default: string;\n"
333                "}\n");
334   verifyFormat("const Axis = {\n"
335                "  for: 'for',\n"
336                "  x: 'x'\n"
337                "};",
338                "const Axis = {for: 'for', x:   'x'};");
339 }
340 
341 TEST_F(FormatTestJS, ReservedWordsMethods) {
342   verifyFormat("class X {\n"
343                "  delete() {\n"
344                "    x();\n"
345                "  }\n"
346                "  interface() {\n"
347                "    x();\n"
348                "  }\n"
349                "  let() {\n"
350                "    x();\n"
351                "  }\n"
352                "}\n");
353   verifyFormat("class KeywordNamedMethods {\n"
354                "  do() {\n"
355                "  }\n"
356                "  for() {\n"
357                "  }\n"
358                "  while() {\n"
359                "  }\n"
360                "  if() {\n"
361                "  }\n"
362                "  else() {\n"
363                "  }\n"
364                "  try() {\n"
365                "  }\n"
366                "  catch() {\n"
367                "  }\n"
368                "}\n");
369 }
370 
371 TEST_F(FormatTestJS, ReservedWordsParenthesized) {
372   // All of these are statements using the keyword, not function calls.
373   verifyFormat("throw (x + y);\n"
374                "await (await x).y;\n"
375                "typeof (x) === 'string';\n"
376                "void (0);\n"
377                "delete (x.y);\n"
378                "return (x);\n");
379 }
380 
381 TEST_F(FormatTestJS, ES6DestructuringAssignment) {
382   verifyFormat("var [a, b, c] = [1, 2, 3];");
383   verifyFormat("const [a, b, c] = [1, 2, 3];");
384   verifyFormat("let [a, b, c] = [1, 2, 3];");
385   verifyFormat("var {a, b} = {a: 1, b: 2};");
386   verifyFormat("let {a, b} = {a: 1, b: 2};");
387 }
388 
389 TEST_F(FormatTestJS, ContainerLiterals) {
390   verifyFormat("var x = {\n"
391                "  y: function(a) {\n"
392                "    return a;\n"
393                "  }\n"
394                "};");
395   verifyFormat("return {\n"
396                "  link: function() {\n"
397                "    f();  //\n"
398                "  }\n"
399                "};");
400   verifyFormat("return {\n"
401                "  a: a,\n"
402                "  link: function() {\n"
403                "    f();  //\n"
404                "  }\n"
405                "};");
406   verifyFormat("return {\n"
407                "  a: a,\n"
408                "  link: function() {\n"
409                "    f();  //\n"
410                "  },\n"
411                "  link: function() {\n"
412                "    f();  //\n"
413                "  }\n"
414                "};");
415   verifyFormat("var stuff = {\n"
416                "  // comment for update\n"
417                "  update: false,\n"
418                "  // comment for modules\n"
419                "  modules: false,\n"
420                "  // comment for tasks\n"
421                "  tasks: false\n"
422                "};");
423   verifyFormat("return {\n"
424                "  'finish':\n"
425                "      //\n"
426                "      a\n"
427                "};");
428   verifyFormat("var obj = {\n"
429                "  fooooooooo: function(x) {\n"
430                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
431                "  }\n"
432                "};");
433   // Simple object literal, as opposed to enum style below.
434   verifyFormat("var obj = {a: 123};");
435   // Enum style top level assignment.
436   verifyFormat("X = {\n  a: 123\n};");
437   verifyFormat("X.Y = {\n  a: 123\n};");
438   // But only on the top level, otherwise its a plain object literal assignment.
439   verifyFormat("function x() {\n"
440                "  y = {z: 1};\n"
441                "}");
442   verifyFormat("x = foo && {a: 123};");
443 
444   // Arrow functions in object literals.
445   verifyFormat("var x = {\n"
446                "  y: (a) => {\n"
447                "    x();\n"
448                "    return a;\n"
449                "  },\n"
450                "};");
451   verifyFormat("var x = {y: (a) => a};");
452 
453   // Methods in object literals.
454   verifyFormat("var x = {\n"
455                "  y(a: string): number {\n"
456                "    return a;\n"
457                "  }\n"
458                "};");
459   verifyFormat("var x = {\n"
460                "  y(a: string) {\n"
461                "    return a;\n"
462                "  }\n"
463                "};");
464 
465   // Computed keys.
466   verifyFormat("var x = {[a]: 1, b: 2, [c]: 3};");
467   verifyFormat("var x = {\n"
468                "  [a]: 1,\n"
469                "  b: 2,\n"
470                "  [c]: 3,\n"
471                "};");
472 
473   // Object literals can leave out labels.
474   verifyFormat("f({a}, () => {\n"
475                "  x;\n"
476                "  g();\n"
477                "});");
478 
479   // Keys can be quoted.
480   verifyFormat("var x = {\n"
481                "  a: a,\n"
482                "  b: b,\n"
483                "  'c': c,\n"
484                "};");
485 
486   // Dict literals can skip the label names.
487   verifyFormat("var x = {\n"
488                "  aaa,\n"
489                "  aaa,\n"
490                "  aaa,\n"
491                "};");
492   verifyFormat("return {\n"
493                "  a,\n"
494                "  b: 'b',\n"
495                "  c,\n"
496                "};");
497 }
498 
499 TEST_F(FormatTestJS, MethodsInObjectLiterals) {
500   verifyFormat("var o = {\n"
501                "  value: 'test',\n"
502                "  get value() {  // getter\n"
503                "    return this.value;\n"
504                "  }\n"
505                "};");
506   verifyFormat("var o = {\n"
507                "  value: 'test',\n"
508                "  set value(val) {  // setter\n"
509                "    this.value = val;\n"
510                "  }\n"
511                "};");
512   verifyFormat("var o = {\n"
513                "  value: 'test',\n"
514                "  someMethod(val) {  // method\n"
515                "    doSomething(this.value + val);\n"
516                "  }\n"
517                "};");
518   verifyFormat("var o = {\n"
519                "  someMethod(val) {  // method\n"
520                "    doSomething(this.value + val);\n"
521                "  },\n"
522                "  someOtherMethod(val) {  // method\n"
523                "    doSomething(this.value + val);\n"
524                "  }\n"
525                "};");
526 }
527 
528 TEST_F(FormatTestJS, GettersSettersVisibilityKeywords) {
529   // Don't break after "protected"
530   verifyFormat("class X {\n"
531                "  protected get getter():\n"
532                "      number {\n"
533                "    return 1;\n"
534                "  }\n"
535                "}",
536                getGoogleJSStyleWithColumns(12));
537   // Don't break after "get"
538   verifyFormat("class X {\n"
539                "  protected get someReallyLongGetterName():\n"
540                "      number {\n"
541                "    return 1;\n"
542                "  }\n"
543                "}",
544                getGoogleJSStyleWithColumns(40));
545 }
546 
547 TEST_F(FormatTestJS, SpacesInContainerLiterals) {
548   verifyFormat("var arr = [1, 2, 3];");
549   verifyFormat("f({a: 1, b: 2, c: 3});");
550 
551   verifyFormat("var object_literal_with_long_name = {\n"
552                "  a: 'aaaaaaaaaaaaaaaaaa',\n"
553                "  b: 'bbbbbbbbbbbbbbbbbb'\n"
554                "};");
555 
556   verifyFormat("f({a: 1, b: 2, c: 3});",
557                getChromiumStyle(FormatStyle::LK_JavaScript));
558   verifyFormat("f({'a': [{}]});");
559 }
560 
561 TEST_F(FormatTestJS, SingleQuotedStrings) {
562   verifyFormat("this.function('', true);");
563 }
564 
565 TEST_F(FormatTestJS, GoogScopes) {
566   verifyFormat("goog.scope(function() {\n"
567                "var x = a.b;\n"
568                "var y = c.d;\n"
569                "});  // goog.scope");
570   verifyFormat("goog.scope(function() {\n"
571                "// test\n"
572                "var x = 0;\n"
573                "// test\n"
574                "});");
575 }
576 
577 TEST_F(FormatTestJS, IIFEs) {
578   // Internal calling parens; no semi.
579   verifyFormat("(function() {\n"
580                "var a = 1;\n"
581                "}())");
582   // External calling parens; no semi.
583   verifyFormat("(function() {\n"
584                "var b = 2;\n"
585                "})()");
586   // Internal calling parens; with semi.
587   verifyFormat("(function() {\n"
588                "var c = 3;\n"
589                "}());");
590   // External calling parens; with semi.
591   verifyFormat("(function() {\n"
592                "var d = 4;\n"
593                "})();");
594 }
595 
596 TEST_F(FormatTestJS, GoogModules) {
597   verifyFormat("goog.module('this.is.really.absurdly.long');",
598                getGoogleJSStyleWithColumns(40));
599   verifyFormat("goog.require('this.is.really.absurdly.long');",
600                getGoogleJSStyleWithColumns(40));
601   verifyFormat("goog.provide('this.is.really.absurdly.long');",
602                getGoogleJSStyleWithColumns(40));
603   verifyFormat("var long = goog.require('this.is.really.absurdly.long');",
604                getGoogleJSStyleWithColumns(40));
605   verifyFormat("const X = goog.requireType('this.is.really.absurdly.long');",
606                getGoogleJSStyleWithColumns(40));
607   verifyFormat("goog.forwardDeclare('this.is.really.absurdly.long');",
608                getGoogleJSStyleWithColumns(40));
609 
610   // These should be wrapped normally.
611   verifyFormat(
612       "var MyLongClassName =\n"
613       "    goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
614   verifyFormat("function a() {\n"
615                "  goog.setTestOnly();\n"
616                "}\n",
617                "function a() {\n"
618                "goog.setTestOnly();\n"
619                "}\n");
620 }
621 
622 TEST_F(FormatTestJS, FormatsNamespaces) {
623   verifyFormat("namespace Foo {\n"
624                "  export let x = 1;\n"
625                "}\n");
626   verifyFormat("declare namespace Foo {\n"
627                "  export let x: number;\n"
628                "}\n");
629 }
630 
631 TEST_F(FormatTestJS, NamespacesMayNotWrap) {
632   verifyFormat("declare namespace foobarbaz {\n"
633                "}\n",
634                getGoogleJSStyleWithColumns(18));
635   verifyFormat("declare module foobarbaz {\n"
636                "}\n",
637                getGoogleJSStyleWithColumns(15));
638   verifyFormat("namespace foobarbaz {\n"
639                "}\n",
640                getGoogleJSStyleWithColumns(10));
641   verifyFormat("module foobarbaz {\n"
642                "}\n",
643                getGoogleJSStyleWithColumns(7));
644 }
645 
646 TEST_F(FormatTestJS, AmbientDeclarations) {
647   FormatStyle NineCols = getGoogleJSStyleWithColumns(9);
648   verifyFormat("declare class\n"
649                "    X {}",
650                NineCols);
651   verifyFormat("declare function\n"
652                "x();", // TODO(martinprobst): should ideally be indented.
653                NineCols);
654   verifyFormat("declare function foo();\n"
655                "let x = 1;\n");
656   verifyFormat("declare function foo(): string;\n"
657                "let x = 1;\n");
658   verifyFormat("declare function foo(): {x: number};\n"
659                "let x = 1;\n");
660   verifyFormat("declare class X {}\n"
661                "let x = 1;\n");
662   verifyFormat("declare interface Y {}\n"
663                "let x = 1;\n");
664   verifyFormat("declare enum X {\n"
665                "}",
666                NineCols);
667   verifyFormat("declare let\n"
668                "    x: number;",
669                NineCols);
670 }
671 
672 TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
673   verifyFormat("function outer1(a, b) {\n"
674                "  function inner1(a, b) {\n"
675                "    return a;\n"
676                "  }\n"
677                "  inner1(a, b);\n"
678                "}\n"
679                "function outer2(a, b) {\n"
680                "  function inner2(a, b) {\n"
681                "    return a;\n"
682                "  }\n"
683                "  inner2(a, b);\n"
684                "}");
685   verifyFormat("function f() {}");
686   verifyFormat("function aFunction() {}\n"
687                "(function f() {\n"
688                "  var x = 1;\n"
689                "}());\n");
690   verifyFormat("function aFunction() {}\n"
691                "{\n"
692                "  let x = 1;\n"
693                "  console.log(x);\n"
694                "}\n");
695   EXPECT_EQ("a = function(x) {}\n"
696             "\n"
697             "function f(x) {}",
698             format("a = function(x) {}\n"
699                    "\n"
700                    "function f(x) {}",
701                    getGoogleJSStyleWithColumns(20)));
702 }
703 
704 TEST_F(FormatTestJS, FormatsDecorators) {
705   // No line break after argument decorators.
706   verifyFormat("class A {\n"
707                "  constructor(@arg(DECOR) private arg: Type) {}\n"
708                "}");
709   // Ensure that there is a break before functions, getters and setters.
710   EXPECT_EQ("class A {\n"
711             "  private p = () => {}\n"
712             "\n"
713             "  @decorated('a')\n"
714             "  get f() {\n"
715             "    return result;\n"
716             "  }\n"
717             "}\n"
718             "\n"
719             "class B {\n"
720             "  private p = () => {}\n"
721             "\n"
722             "  @decorated('a')\n"
723             "  set f() {\n"
724             "    return result;\n"
725             "  }\n"
726             "}\n"
727             "\n"
728             "class C {\n"
729             "  private p = () => {}\n"
730             "\n"
731             "  @decorated('a')\n"
732             "  function f() {\n"
733             "    return result;\n"
734             "  }\n"
735             "}",
736             format("class A {\n"
737                    "  private p = () => {}\n"
738                    "\n"
739                    "  @decorated('a')\n"
740                    "  get f() {\n"
741                    "    return result;\n"
742                    "  }\n"
743                    "}\n"
744                    "\n"
745                    "class B {\n"
746                    "  private p = () => {}\n"
747                    "\n"
748                    "  @decorated('a')\n"
749                    "  set f() {\n"
750                    "    return result;\n"
751                    "  }\n"
752                    "}\n"
753                    "\n"
754                    "class C {\n"
755                    "  private p = () => {}\n"
756                    "\n"
757                    "  @decorated('a')\n"
758                    "  function f() {\n"
759                    "    return result;\n"
760                    "  }\n"
761                    "}",
762                    getGoogleJSStyleWithColumns(50)));
763 }
764 
765 TEST_F(FormatTestJS, GeneratorFunctions) {
766   verifyFormat("function* f() {\n"
767                "  let x = 1;\n"
768                "  yield x;\n"
769                "  yield* something();\n"
770                "  yield [1, 2];\n"
771                "  yield {a: 1};\n"
772                "}");
773   verifyFormat("function*\n"
774                "    f() {\n"
775                "}",
776                getGoogleJSStyleWithColumns(8));
777   verifyFormat("export function* f() {\n"
778                "  yield 1;\n"
779                "}\n");
780   verifyFormat("class X {\n"
781                "  * generatorMethod() {\n"
782                "    yield x;\n"
783                "  }\n"
784                "}");
785   verifyFormat("var x = {\n"
786                "  a: function*() {\n"
787                "    //\n"
788                "  }\n"
789                "}\n");
790 }
791 
792 TEST_F(FormatTestJS, AsyncFunctions) {
793   verifyFormat("async function f() {\n"
794                "  let x = 1;\n"
795                "  return fetch(x);\n"
796                "}");
797   verifyFormat("async function f() {\n"
798                "  return 1;\n"
799                "}\n"
800                "\n"
801                "function a() {\n"
802                "  return 1;\n"
803                "}\n",
804                "  async   function f() {\n"
805                "   return 1;\n"
806                "}\n"
807                "\n"
808                "   function a() {\n"
809                "  return   1;\n"
810                "}  \n");
811   // clang-format must not insert breaks between async and function, otherwise
812   // automatic semicolon insertion may trigger (in particular in a class body).
813   verifyFormat("async function\n"
814                "hello(\n"
815                "    myparamnameiswaytooloooong) {\n"
816                "}",
817                "async function hello(myparamnameiswaytooloooong) {}",
818                getGoogleJSStyleWithColumns(10));
819   verifyFormat("class C {\n"
820                "  async hello(\n"
821                "      myparamnameiswaytooloooong) {\n"
822                "  }\n"
823                "}",
824                "class C {\n"
825                "  async hello(myparamnameiswaytooloooong) {} }",
826                getGoogleJSStyleWithColumns(10));
827   verifyFormat("async function* f() {\n"
828                "  yield fetch(x);\n"
829                "}");
830   verifyFormat("export async function f() {\n"
831                "  return fetch(x);\n"
832                "}");
833   verifyFormat("let x = async () => f();");
834   verifyFormat("let x = async function() {\n"
835                "  f();\n"
836                "};");
837   verifyFormat("let x = async();");
838   verifyFormat("class X {\n"
839                "  async asyncMethod() {\n"
840                "    return fetch(1);\n"
841                "  }\n"
842                "}");
843   verifyFormat("function initialize() {\n"
844                "  // Comment.\n"
845                "  return async.then();\n"
846                "}\n");
847   verifyFormat("for await (const x of y) {\n"
848                "  console.log(x);\n"
849                "}\n");
850   verifyFormat("function asyncLoop() {\n"
851                "  for await (const x of y) {\n"
852                "    console.log(x);\n"
853                "  }\n"
854                "}\n");
855 }
856 
857 TEST_F(FormatTestJS, FunctionParametersTrailingComma) {
858   verifyFormat("function trailingComma(\n"
859                "    p1,\n"
860                "    p2,\n"
861                "    p3,\n"
862                ") {\n"
863                "  a;  //\n"
864                "}\n",
865                "function trailingComma(p1, p2, p3,) {\n"
866                "  a;  //\n"
867                "}\n");
868   verifyFormat("trailingComma(\n"
869                "    p1,\n"
870                "    p2,\n"
871                "    p3,\n"
872                ");\n",
873                "trailingComma(p1, p2, p3,);\n");
874   verifyFormat("trailingComma(\n"
875                "    p1  // hello\n"
876                ");\n",
877                "trailingComma(p1 // hello\n"
878                ");\n");
879 }
880 
881 TEST_F(FormatTestJS, ArrayLiterals) {
882   verifyFormat("var aaaaa: List<SomeThing> =\n"
883                "    [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];");
884   verifyFormat("return [\n"
885                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
886                "  ccccccccccccccccccccccccccc\n"
887                "];");
888   verifyFormat("return [\n"
889                "  aaaa().bbbbbbbb('A'),\n"
890                "  aaaa().bbbbbbbb('B'),\n"
891                "  aaaa().bbbbbbbb('C'),\n"
892                "];");
893   verifyFormat("var someVariable = SomeFunction([\n"
894                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
895                "  ccccccccccccccccccccccccccc\n"
896                "]);");
897   verifyFormat("var someVariable = SomeFunction([\n"
898                "  [aaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbb],\n"
899                "]);",
900                getGoogleJSStyleWithColumns(51));
901   verifyFormat("var someVariable = SomeFunction(aaaa, [\n"
902                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
903                "  ccccccccccccccccccccccccccc\n"
904                "]);");
905   verifyFormat("var someVariable = SomeFunction(\n"
906                "    aaaa,\n"
907                "    [\n"
908                "      aaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
909                "      cccccccccccccccccccccccccc\n"
910                "    ],\n"
911                "    aaaa);");
912   verifyFormat("var aaaa = aaaaa ||  // wrap\n"
913                "    [];");
914 
915   verifyFormat("someFunction([], {a: a});");
916 
917   verifyFormat("var string = [\n"
918                "  'aaaaaa',\n"
919                "  'bbbbbb',\n"
920                "].join('+');");
921 }
922 
923 TEST_F(FormatTestJS, ColumnLayoutForArrayLiterals) {
924   verifyFormat("var array = [\n"
925                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
926                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
927                "];");
928   verifyFormat("var array = someFunction([\n"
929                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
930                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
931                "]);");
932 }
933 
934 TEST_F(FormatTestJS, TrailingCommaInsertion) {
935   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
936   Style.InsertTrailingCommas = FormatStyle::TCS_Wrapped;
937   // Insert comma in wrapped array.
938   verifyFormat("const x = [\n"
939                "  1,  //\n"
940                "  2,\n"
941                "];",
942                "const x = [\n"
943                "  1,  //\n"
944                "  2];",
945                Style);
946   // Insert comma in newly wrapped array.
947   Style.ColumnLimit = 30;
948   verifyFormat("const x = [\n"
949                "  aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
950                "];",
951                "const x = [aaaaaaaaaaaaaaaaaaaaaaaaa];", Style);
952   // Do not insert trailing commas if they'd exceed the colum limit
953   verifyFormat("const x = [\n"
954                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
955                "];",
956                "const x = [aaaaaaaaaaaaaaaaaaaaaaaaaaaa];", Style);
957   // Object literals.
958   verifyFormat("const x = {\n"
959                "  a: aaaaaaaaaaaaaaaaa,\n"
960                "};",
961                "const x = {a: aaaaaaaaaaaaaaaaa};", Style);
962   verifyFormat("const x = {\n"
963                "  a: aaaaaaaaaaaaaaaaaaaaaaaaa\n"
964                "};",
965                "const x = {a: aaaaaaaaaaaaaaaaaaaaaaaaa};", Style);
966   // Object literal types.
967   verifyFormat("let x: {\n"
968                "  a: aaaaaaaaaaaaaaaaaaaaa,\n"
969                "};",
970                "let x: {a: aaaaaaaaaaaaaaaaaaaaa};", Style);
971 }
972 
973 TEST_F(FormatTestJS, FunctionLiterals) {
974   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
975   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
976   verifyFormat("doFoo(function() {});");
977   verifyFormat("doFoo(function() { return 1; });", Style);
978   verifyFormat("var func = function() {\n"
979                "  return 1;\n"
980                "};");
981   verifyFormat("var func =  //\n"
982                "    function() {\n"
983                "  return 1;\n"
984                "};");
985   verifyFormat("return {\n"
986                "  body: {\n"
987                "    setAttribute: function(key, val) { this[key] = val; },\n"
988                "    getAttribute: function(key) { return this[key]; },\n"
989                "    style: {direction: ''}\n"
990                "  }\n"
991                "};",
992                Style);
993   verifyFormat("abc = xyz ? function() {\n"
994                "  return 1;\n"
995                "} : function() {\n"
996                "  return -1;\n"
997                "};");
998 
999   verifyFormat("var closure = goog.bind(\n"
1000                "    function() {  // comment\n"
1001                "      foo();\n"
1002                "      bar();\n"
1003                "    },\n"
1004                "    this, arg1IsReallyLongAndNeedsLineBreaks,\n"
1005                "    arg3IsReallyLongAndNeedsLineBreaks);");
1006   verifyFormat("var closure = goog.bind(function() {  // comment\n"
1007                "  foo();\n"
1008                "  bar();\n"
1009                "}, this);");
1010   verifyFormat("return {\n"
1011                "  a: 'E',\n"
1012                "  b: function() {\n"
1013                "    return function() {\n"
1014                "      f();  //\n"
1015                "    };\n"
1016                "  }\n"
1017                "};");
1018   verifyFormat("{\n"
1019                "  var someVariable = function(x) {\n"
1020                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
1021                "  };\n"
1022                "}");
1023   verifyFormat("someLooooooooongFunction(\n"
1024                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1025                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1026                "    function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1027                "      // code\n"
1028                "    });");
1029 
1030   verifyFormat("return {\n"
1031                "  a: function SomeFunction() {\n"
1032                "    // ...\n"
1033                "    return 1;\n"
1034                "  }\n"
1035                "};");
1036   verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
1037                "    .then(goog.bind(function(aaaaaaaaaaa) {\n"
1038                "      someFunction();\n"
1039                "      someFunction();\n"
1040                "    }, this), aaaaaaaaaaaaaaaaa);");
1041 
1042   verifyFormat("someFunction(goog.bind(function() {\n"
1043                "  doSomething();\n"
1044                "  doSomething();\n"
1045                "}, this), goog.bind(function() {\n"
1046                "  doSomething();\n"
1047                "  doSomething();\n"
1048                "}, this));");
1049 
1050   verifyFormat("SomeFunction(function() {\n"
1051                "  foo();\n"
1052                "  bar();\n"
1053                "}.bind(this));");
1054 
1055   verifyFormat("SomeFunction((function() {\n"
1056                "               foo();\n"
1057                "               bar();\n"
1058                "             }).bind(this));");
1059 
1060   // FIXME: This is bad, we should be wrapping before "function() {".
1061   verifyFormat("someFunction(function() {\n"
1062                "  doSomething();  // break\n"
1063                "})\n"
1064                "    .doSomethingElse(\n"
1065                "        // break\n"
1066                "    );");
1067 
1068   Style.ColumnLimit = 33;
1069   verifyFormat("f({a: function() { return 1; }});", Style);
1070   Style.ColumnLimit = 32;
1071   verifyFormat("f({\n"
1072                "  a: function() { return 1; }\n"
1073                "});",
1074                Style);
1075 }
1076 
1077 TEST_F(FormatTestJS, DontWrapEmptyLiterals) {
1078   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
1079                "    .and.returnValue(Observable.of([]));");
1080   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
1081                "    .and.returnValue(Observable.of({}));");
1082   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
1083                "    .and.returnValue(Observable.of(()));");
1084 }
1085 
1086 TEST_F(FormatTestJS, InliningFunctionLiterals) {
1087   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
1088   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
1089   verifyFormat("var func = function() {\n"
1090                "  return 1;\n"
1091                "};",
1092                Style);
1093   verifyFormat("var func = doSomething(function() { return 1; });", Style);
1094   verifyFormat("var outer = function() {\n"
1095                "  var inner = function() { return 1; }\n"
1096                "};",
1097                Style);
1098   verifyFormat("function outer1(a, b) {\n"
1099                "  function inner1(a, b) { return a; }\n"
1100                "}",
1101                Style);
1102 
1103   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1104   verifyFormat("var func = function() { return 1; };", Style);
1105   verifyFormat("var func = doSomething(function() { return 1; });", Style);
1106   verifyFormat(
1107       "var outer = function() { var inner = function() { return 1; } };",
1108       Style);
1109   verifyFormat("function outer1(a, b) {\n"
1110                "  function inner1(a, b) { return a; }\n"
1111                "}",
1112                Style);
1113 
1114   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
1115   verifyFormat("var func = function() {\n"
1116                "  return 1;\n"
1117                "};",
1118                Style);
1119   verifyFormat("var func = doSomething(function() {\n"
1120                "  return 1;\n"
1121                "});",
1122                Style);
1123   verifyFormat("var outer = function() {\n"
1124                "  var inner = function() {\n"
1125                "    return 1;\n"
1126                "  }\n"
1127                "};",
1128                Style);
1129   verifyFormat("function outer1(a, b) {\n"
1130                "  function inner1(a, b) {\n"
1131                "    return a;\n"
1132                "  }\n"
1133                "}",
1134                Style);
1135 
1136   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1137   verifyFormat("var func = function() {\n"
1138                "  return 1;\n"
1139                "};",
1140                Style);
1141 }
1142 
1143 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
1144   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
1145   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1146   verifyFormat("promise.then(\n"
1147                "    function success() {\n"
1148                "      doFoo();\n"
1149                "      doBar();\n"
1150                "    },\n"
1151                "    function error() {\n"
1152                "      doFoo();\n"
1153                "      doBaz();\n"
1154                "    },\n"
1155                "    []);\n");
1156   verifyFormat("promise.then(\n"
1157                "    function success() {\n"
1158                "      doFoo();\n"
1159                "      doBar();\n"
1160                "    },\n"
1161                "    [],\n"
1162                "    function error() {\n"
1163                "      doFoo();\n"
1164                "      doBaz();\n"
1165                "    });\n");
1166   verifyFormat("promise.then(\n"
1167                "    [],\n"
1168                "    function success() {\n"
1169                "      doFoo();\n"
1170                "      doBar();\n"
1171                "    },\n"
1172                "    function error() {\n"
1173                "      doFoo();\n"
1174                "      doBaz();\n"
1175                "    });\n");
1176 
1177   verifyFormat("getSomeLongPromise()\n"
1178                "    .then(function(value) { body(); })\n"
1179                "    .thenCatch(function(error) {\n"
1180                "      body();\n"
1181                "      body();\n"
1182                "    });",
1183                Style);
1184   verifyFormat("getSomeLongPromise()\n"
1185                "    .then(function(value) {\n"
1186                "      body();\n"
1187                "      body();\n"
1188                "    })\n"
1189                "    .thenCatch(function(error) {\n"
1190                "      body();\n"
1191                "      body();\n"
1192                "    });");
1193 
1194   verifyFormat("getSomeLongPromise()\n"
1195                "    .then(function(value) { body(); })\n"
1196                "    .thenCatch(function(error) { body(); });",
1197                Style);
1198 
1199   verifyFormat("return [aaaaaaaaaaaaaaaaaaaaaa]\n"
1200                "    .aaaaaaa(function() {\n"
1201                "      //\n"
1202                "    })\n"
1203                "    .bbbbbb();");
1204 }
1205 
1206 TEST_F(FormatTestJS, ArrowFunctions) {
1207   verifyFormat("var x = (a) => {\n"
1208                "  x;\n"
1209                "  return a;\n"
1210                "};\n");
1211   verifyFormat("var x = (a) => {\n"
1212                "  function y() {\n"
1213                "    return 42;\n"
1214                "  }\n"
1215                "  return a;\n"
1216                "};");
1217   verifyFormat("var x = (a: type): {some: type} => {\n"
1218                "  y;\n"
1219                "  return a;\n"
1220                "};");
1221   verifyFormat("var x = (a) => a;");
1222   verifyFormat("return () => [];");
1223   verifyFormat("var aaaaaaaaaaaaaaaaaaaa = {\n"
1224                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
1225                "      (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1226                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) =>\n"
1227                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1228                "};");
1229   verifyFormat("var a = a.aaaaaaa(\n"
1230                "    (a: a) => aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) &&\n"
1231                "        aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
1232   verifyFormat("var a = a.aaaaaaa(\n"
1233                "    (a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) ?\n"
1234                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb) :\n"
1235                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
1236 
1237   // FIXME: This is bad, we should be wrapping before "() => {".
1238   verifyFormat("someFunction(() => {\n"
1239                "  doSomething();  // break\n"
1240                "})\n"
1241                "    .doSomethingElse(\n"
1242                "        // break\n"
1243                "    );");
1244   verifyFormat("const f = (x: string|null): string|null => {\n"
1245                "  y;\n"
1246                "  return x;\n"
1247                "}\n");
1248 }
1249 
1250 TEST_F(FormatTestJS, ArrowFunctionStyle) {
1251   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
1252   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
1253   verifyFormat("const arr = () => { x; };", Style);
1254   verifyFormat("const arrInlineAll = () => {};", Style);
1255   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
1256   verifyFormat("const arr = () => {\n"
1257                "  x;\n"
1258                "};",
1259                Style);
1260   verifyFormat("const arrInlineNone = () => {\n"
1261                "};",
1262                Style);
1263   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
1264   verifyFormat("const arr = () => {\n"
1265                "  x;\n"
1266                "};",
1267                Style);
1268   verifyFormat("const arrInlineEmpty = () => {};", Style);
1269   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
1270   verifyFormat("const arr = () => {\n"
1271                "  x;\n"
1272                "};",
1273                Style);
1274   verifyFormat("foo(() => {});", Style);
1275   verifyFormat("const arrInlineInline = () => {};", Style);
1276 }
1277 
1278 TEST_F(FormatTestJS, ReturnStatements) {
1279   verifyFormat("function() {\n"
1280                "  return [hello, world];\n"
1281                "}");
1282 }
1283 
1284 TEST_F(FormatTestJS, ForLoops) {
1285   verifyFormat("for (var i in [2, 3]) {\n"
1286                "}");
1287   verifyFormat("for (var i of [2, 3]) {\n"
1288                "}");
1289   verifyFormat("for (let {a, b} of x) {\n"
1290                "}");
1291   verifyFormat("for (let {a, b} of [x]) {\n"
1292                "}");
1293   verifyFormat("for (let [a, b] of [x]) {\n"
1294                "}");
1295   verifyFormat("for (let {a, b} in x) {\n"
1296                "}");
1297 }
1298 
1299 TEST_F(FormatTestJS, WrapRespectsAutomaticSemicolonInsertion) {
1300   // The following statements must not wrap, as otherwise the program meaning
1301   // would change due to automatic semicolon insertion.
1302   // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
1303   verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10));
1304   verifyFormat("yield aaaaa;", getGoogleJSStyleWithColumns(10));
1305   verifyFormat("return /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10));
1306   verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10));
1307   verifyFormat("continue /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10));
1308   verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10));
1309   verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
1310   verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
1311   verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
1312   verifyFormat("return [\n"
1313                "  aaa\n"
1314                "];",
1315                getGoogleJSStyleWithColumns(12));
1316   verifyFormat("class X {\n"
1317                "  readonly ratherLongField =\n"
1318                "      1;\n"
1319                "}",
1320                "class X {\n"
1321                "  readonly ratherLongField = 1;\n"
1322                "}",
1323                getGoogleJSStyleWithColumns(20));
1324   verifyFormat("const x = (5 + 9)\n"
1325                "const y = 3\n",
1326                "const x = (   5 +    9)\n"
1327                "const y = 3\n");
1328   // Ideally the foo() bit should be indented relative to the async function().
1329   verifyFormat("async function\n"
1330                "foo() {}",
1331                getGoogleJSStyleWithColumns(10));
1332   verifyFormat("await theReckoning;", getGoogleJSStyleWithColumns(10));
1333   verifyFormat("some['a']['b']", getGoogleJSStyleWithColumns(10));
1334   verifyFormat("x = (a['a']\n"
1335                "      ['b']);",
1336                getGoogleJSStyleWithColumns(10));
1337   verifyFormat("function f() {\n"
1338                "  return foo.bar(\n"
1339                "      (param): param is {\n"
1340                "        a: SomeType\n"
1341                "      }&ABC => 1)\n"
1342                "}",
1343                getGoogleJSStyleWithColumns(25));
1344 }
1345 
1346 TEST_F(FormatTestJS, AddsIsTheDictKeyOnNewline) {
1347   // Do not confuse is, the dict key with is, the type matcher. Put is, the dict
1348   // key, on a newline.
1349   verifyFormat("Polymer({\n"
1350                "  is: '',  //\n"
1351                "  rest: 1\n"
1352                "});",
1353                getGoogleJSStyleWithColumns(20));
1354 }
1355 
1356 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
1357   verifyFormat("a\n"
1358                "b;",
1359                " a \n"
1360                " b ;");
1361   verifyFormat("a()\n"
1362                "b;",
1363                " a ()\n"
1364                " b ;");
1365   verifyFormat("a[b]\n"
1366                "c;",
1367                "a [b]\n"
1368                "c ;");
1369   verifyFormat("1\n"
1370                "a;",
1371                "1 \n"
1372                "a ;");
1373   verifyFormat("a\n"
1374                "1;",
1375                "a \n"
1376                "1 ;");
1377   verifyFormat("a\n"
1378                "'x';",
1379                "a \n"
1380                " 'x';");
1381   verifyFormat("a++\n"
1382                "b;",
1383                "a ++\n"
1384                "b ;");
1385   verifyFormat("a\n"
1386                "!b && c;",
1387                "a \n"
1388                " ! b && c;");
1389   verifyFormat("a\n"
1390                "if (1) f();",
1391                " a\n"
1392                " if (1) f();");
1393   verifyFormat("a\n"
1394                "class X {}",
1395                " a\n"
1396                " class X {}");
1397   verifyFormat("var a", "var\n"
1398                         "a");
1399   verifyFormat("x instanceof String", "x\n"
1400                                       "instanceof\n"
1401                                       "String");
1402   verifyFormat("function f(@Foo bar) {}", "function f(@Foo\n"
1403                                           "  bar) {}");
1404   verifyFormat("function f(@Foo(Param) bar) {}", "function f(@Foo(Param)\n"
1405                                                  "  bar) {}");
1406   verifyFormat("a = true\n"
1407                "return 1",
1408                "a = true\n"
1409                "  return   1");
1410   verifyFormat("a = 's'\n"
1411                "return 1",
1412                "a = 's'\n"
1413                "  return   1");
1414   verifyFormat("a = null\n"
1415                "return 1",
1416                "a = null\n"
1417                "  return   1");
1418   // Below "class Y {}" should ideally be on its own line.
1419   verifyFormat("x = {\n"
1420                "  a: 1\n"
1421                "} class Y {}",
1422                "  x  =  {a  : 1}\n"
1423                "   class  Y {  }");
1424   verifyFormat("if (x) {\n"
1425                "}\n"
1426                "return 1",
1427                "if (x) {}\n"
1428                " return   1");
1429   verifyFormat("if (x) {\n"
1430                "}\n"
1431                "class X {}",
1432                "if (x) {}\n"
1433                " class X {}");
1434 }
1435 
1436 TEST_F(FormatTestJS, ImportExportASI) {
1437   verifyFormat("import {x} from 'y'\n"
1438                "export function z() {}",
1439                "import   {x} from 'y'\n"
1440                "  export function z() {}");
1441   // Below "class Y {}" should ideally be on its own line.
1442   verifyFormat("export {x} class Y {}", "  export {x}\n"
1443                                         "  class  Y {\n}");
1444   verifyFormat("if (x) {\n"
1445                "}\n"
1446                "export class Y {}",
1447                "if ( x ) { }\n"
1448                " export class Y {}");
1449 }
1450 
1451 TEST_F(FormatTestJS, ClosureStyleCasts) {
1452   verifyFormat("var x = /** @type {foo} */ (bar);");
1453 }
1454 
1455 TEST_F(FormatTestJS, TryCatch) {
1456   verifyFormat("try {\n"
1457                "  f();\n"
1458                "} catch (e) {\n"
1459                "  g();\n"
1460                "} finally {\n"
1461                "  h();\n"
1462                "}");
1463 
1464   // But, of course, "catch" is a perfectly fine function name in JavaScript.
1465   verifyFormat("someObject.catch();");
1466   verifyFormat("someObject.new();");
1467 }
1468 
1469 TEST_F(FormatTestJS, StringLiteralConcatenation) {
1470   verifyFormat("var literal = 'hello ' +\n"
1471                "    'world';");
1472 }
1473 
1474 TEST_F(FormatTestJS, RegexLiteralClassification) {
1475   // Regex literals.
1476   verifyFormat("var regex = /abc/;");
1477   verifyFormat("f(/abc/);");
1478   verifyFormat("f(abc, /abc/);");
1479   verifyFormat("some_map[/abc/];");
1480   verifyFormat("var x = a ? /abc/ : /abc/;");
1481   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
1482   verifyFormat("var x = !/abc/.test(y);");
1483   verifyFormat("var x = foo()! / 10;");
1484   verifyFormat("var x = a && /abc/.test(y);");
1485   verifyFormat("var x = a || /abc/.test(y);");
1486   verifyFormat("var x = a + /abc/.search(y);");
1487   verifyFormat("/abc/.search(y);");
1488   verifyFormat("var regexs = {/abc/, /abc/};");
1489   verifyFormat("return /abc/;");
1490 
1491   // Not regex literals.
1492   verifyFormat("var a = a / 2 + b / 3;");
1493   verifyFormat("var a = a++ / 2;");
1494   // Prefix unary can operate on regex literals, not that it makes sense.
1495   verifyFormat("var a = ++/a/;");
1496 
1497   // This is a known issue, regular expressions are incorrectly detected if
1498   // directly following a closing parenthesis.
1499   verifyFormat("if (foo) / bar /.exec(baz);");
1500 }
1501 
1502 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
1503   verifyFormat("var regex = /=/;");
1504   verifyFormat("var regex = /a*/;");
1505   verifyFormat("var regex = /a+/;");
1506   verifyFormat("var regex = /a?/;");
1507   verifyFormat("var regex = /.a./;");
1508   verifyFormat("var regex = /a\\*/;");
1509   verifyFormat("var regex = /^a$/;");
1510   verifyFormat("var regex = /\\/a/;");
1511   verifyFormat("var regex = /(?:x)/;");
1512   verifyFormat("var regex = /x(?=y)/;");
1513   verifyFormat("var regex = /x(?!y)/;");
1514   verifyFormat("var regex = /x|y/;");
1515   verifyFormat("var regex = /a{2}/;");
1516   verifyFormat("var regex = /a{1,3}/;");
1517 
1518   verifyFormat("var regex = /[abc]/;");
1519   verifyFormat("var regex = /[^abc]/;");
1520   verifyFormat("var regex = /[\\b]/;");
1521   verifyFormat("var regex = /[/]/;");
1522   verifyFormat("var regex = /[\\/]/;");
1523   verifyFormat("var regex = /\\[/;");
1524   verifyFormat("var regex = /\\\\[/]/;");
1525   verifyFormat("var regex = /}[\"]/;");
1526   verifyFormat("var regex = /}[/\"]/;");
1527   verifyFormat("var regex = /}[\"/]/;");
1528 
1529   verifyFormat("var regex = /\\b/;");
1530   verifyFormat("var regex = /\\B/;");
1531   verifyFormat("var regex = /\\d/;");
1532   verifyFormat("var regex = /\\D/;");
1533   verifyFormat("var regex = /\\f/;");
1534   verifyFormat("var regex = /\\n/;");
1535   verifyFormat("var regex = /\\r/;");
1536   verifyFormat("var regex = /\\s/;");
1537   verifyFormat("var regex = /\\S/;");
1538   verifyFormat("var regex = /\\t/;");
1539   verifyFormat("var regex = /\\v/;");
1540   verifyFormat("var regex = /\\w/;");
1541   verifyFormat("var regex = /\\W/;");
1542   verifyFormat("var regex = /a(a)\\1/;");
1543   verifyFormat("var regex = /\\0/;");
1544   verifyFormat("var regex = /\\\\/g;");
1545   verifyFormat("var regex = /\\a\\\\/g;");
1546   verifyFormat("var regex = /\a\\//g;");
1547   verifyFormat("var regex = /a\\//;\n"
1548                "var x = 0;");
1549   verifyFormat("var regex = /'/g;", "var regex = /'/g ;");
1550   verifyFormat("var regex = /'/g;  //'", "var regex = /'/g ; //'");
1551   verifyFormat("var regex = /\\/*/;\n"
1552                "var x = 0;",
1553                "var regex = /\\/*/;\n"
1554                "var x=0;");
1555   verifyFormat("var x = /a\\//;", "var x = /a\\//  \n;");
1556   verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
1557   verifyFormat("var regex =\n"
1558                "    /\"/;",
1559                getGoogleJSStyleWithColumns(15));
1560   verifyFormat("var regex =  //\n"
1561                "    /a/;");
1562   verifyFormat("var regexs = [\n"
1563                "  /d/,   //\n"
1564                "  /aa/,  //\n"
1565                "];");
1566 }
1567 
1568 TEST_F(FormatTestJS, RegexLiteralModifiers) {
1569   verifyFormat("var regex = /abc/g;");
1570   verifyFormat("var regex = /abc/i;");
1571   verifyFormat("var regex = /abc/m;");
1572   verifyFormat("var regex = /abc/y;");
1573 }
1574 
1575 TEST_F(FormatTestJS, RegexLiteralLength) {
1576   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1577                getGoogleJSStyleWithColumns(60));
1578   verifyFormat("var regex =\n"
1579                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1580                getGoogleJSStyleWithColumns(60));
1581   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1582                getGoogleJSStyleWithColumns(50));
1583 }
1584 
1585 TEST_F(FormatTestJS, RegexLiteralExamples) {
1586   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
1587 }
1588 
1589 TEST_F(FormatTestJS, IgnoresMpegTS) {
1590   std::string MpegTS(200, ' ');
1591   MpegTS.replace(0, strlen("nearlyLooks  +   like +   ts + code;  "),
1592                  "nearlyLooks  +   like +   ts + code;  ");
1593   MpegTS[0] = 0x47;
1594   MpegTS[188] = 0x47;
1595   verifyFormat(MpegTS, MpegTS);
1596 }
1597 
1598 TEST_F(FormatTestJS, TypeAnnotations) {
1599   verifyFormat("var x: string;");
1600   verifyFormat("var x: {a: string; b: number;} = {};");
1601   verifyFormat("function x(): string {\n  return 'x';\n}");
1602   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
1603   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
1604   verifyFormat("for (var y: string in x) {\n  x();\n}");
1605   verifyFormat("for (var y: string of x) {\n  x();\n}");
1606   verifyFormat("function x(y: {a?: number;} = {}): number {\n"
1607                "  return 12;\n"
1608                "}");
1609   verifyFormat("const x: Array<{a: number; b: string;}> = [];");
1610   verifyFormat("((a: string, b: number): string => a + b);");
1611   verifyFormat("var x: (y: number) => string;");
1612   verifyFormat("var x: P<string, (a: number) => string>;");
1613   verifyFormat("var x = {\n"
1614                "  y: function(): z {\n"
1615                "    return 1;\n"
1616                "  }\n"
1617                "};");
1618   verifyFormat("var x = {\n"
1619                "  y: function(): {a: number} {\n"
1620                "    return 1;\n"
1621                "  }\n"
1622                "};");
1623   verifyFormat("function someFunc(args: string[]):\n"
1624                "    {longReturnValue: string[]} {}",
1625                getGoogleJSStyleWithColumns(60));
1626   verifyFormat(
1627       "var someValue = (v as aaaaaaaaaaaaaaaaaaaa<T>[])\n"
1628       "                    .someFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1629   verifyFormat("const xIsALongIdent:\n"
1630                "    YJustBarelyFitsLinex[];",
1631                getGoogleJSStyleWithColumns(20));
1632   verifyFormat("const x = {\n"
1633                "  y: 1\n"
1634                "} as const;");
1635 }
1636 
1637 TEST_F(FormatTestJS, UnionIntersectionTypes) {
1638   verifyFormat("let x: A|B = A | B;");
1639   verifyFormat("let x: A&B|C = A & B;");
1640   verifyFormat("let x: Foo<A|B> = new Foo<A|B>();");
1641   verifyFormat("function(x: A|B): C&D {}");
1642   verifyFormat("function(x: A|B = A | B): C&D {}");
1643   verifyFormat("function x(path: number|string) {}");
1644   verifyFormat("function x(): string|number {}");
1645   verifyFormat("type Foo = Bar|Baz;");
1646   verifyFormat("type Foo = Bar<X>|Baz;");
1647   verifyFormat("type Foo = (Bar<X>|Baz);");
1648   verifyFormat("let x: Bar|Baz;");
1649   verifyFormat("let x: Bar<X>|Baz;");
1650   verifyFormat("let x: (Foo|Bar)[];");
1651   verifyFormat("type X = {\n"
1652                "  a: Foo|Bar;\n"
1653                "};");
1654   verifyFormat("export type X = {\n"
1655                "  a: Foo|Bar;\n"
1656                "};");
1657 }
1658 
1659 TEST_F(FormatTestJS, UnionIntersectionTypesInObjectType) {
1660   verifyFormat("let x: {x: number|null} = {x: number | null};");
1661   verifyFormat("let nested: {x: {y: number|null}};");
1662   verifyFormat("let mixed: {x: [number|null, {w: number}]};");
1663   verifyFormat("class X {\n"
1664                "  contructor(x: {\n"
1665                "    a: a|null,\n"
1666                "    b: b|null,\n"
1667                "  }) {}\n"
1668                "}");
1669 }
1670 
1671 TEST_F(FormatTestJS, ClassDeclarations) {
1672   verifyFormat("class C {\n  x: string = 12;\n}");
1673   verifyFormat("class C {\n  x(): string => 12;\n}");
1674   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
1675   verifyFormat("class C {\n"
1676                "  foo() {}\n"
1677                "  [bar]() {}\n"
1678                "}\n");
1679   verifyFormat("class C {\n  private x: string = 12;\n}");
1680   verifyFormat("class C {\n  private static x: string = 12;\n}");
1681   verifyFormat("class C {\n  static x(): string {\n    return 'asd';\n  }\n}");
1682   verifyFormat("class C extends P implements I {}");
1683   verifyFormat("class C extends p.P implements i.I {}");
1684   verifyFormat("x(class {\n"
1685                "  a(): A {}\n"
1686                "});");
1687   verifyFormat("class Test {\n"
1688                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
1689                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
1690                "}");
1691   verifyFormat("foo = class Name {\n"
1692                "  constructor() {}\n"
1693                "};");
1694   verifyFormat("foo = class {\n"
1695                "  constructor() {}\n"
1696                "};");
1697   verifyFormat("class C {\n"
1698                "  x: {y: Z;} = {};\n"
1699                "  private y: {y: Z;} = {};\n"
1700                "}");
1701 
1702   // ':' is not a type declaration here.
1703   verifyFormat("class X {\n"
1704                "  subs = {\n"
1705                "    'b': {\n"
1706                "      'c': 1,\n"
1707                "    },\n"
1708                "  };\n"
1709                "}");
1710   verifyFormat("@Component({\n"
1711                "  moduleId: module.id,\n"
1712                "})\n"
1713                "class SessionListComponent implements OnDestroy, OnInit {\n"
1714                "}");
1715 }
1716 
1717 TEST_F(FormatTestJS, StrictPropInitWrap) {
1718   const FormatStyle &Style = getGoogleJSStyleWithColumns(22);
1719   verifyFormat("class X {\n"
1720                "  strictPropInitField!:\n"
1721                "      string;\n"
1722                "}",
1723                Style);
1724 }
1725 
1726 TEST_F(FormatTestJS, InterfaceDeclarations) {
1727   verifyFormat("interface I {\n"
1728                "  x: string;\n"
1729                "  enum: string[];\n"
1730                "  enum?: string[];\n"
1731                "}\n"
1732                "var y;");
1733   // Ensure that state is reset after parsing the interface.
1734   verifyFormat("interface a {}\n"
1735                "export function b() {}\n"
1736                "var x;");
1737 
1738   // Arrays of object type literals.
1739   verifyFormat("interface I {\n"
1740                "  o: {}[];\n"
1741                "}");
1742 }
1743 
1744 TEST_F(FormatTestJS, ObjectTypesInExtendsImplements) {
1745   verifyFormat("class C extends {} {}");
1746   verifyFormat("class C implements {bar: number} {}");
1747   // Somewhat odd, but probably closest to reasonable formatting?
1748   verifyFormat("class C implements {\n"
1749                "  bar: number,\n"
1750                "  baz: string,\n"
1751                "} {}");
1752   verifyFormat("class C<P extends {}> {}");
1753 }
1754 
1755 TEST_F(FormatTestJS, EnumDeclarations) {
1756   verifyFormat("enum Foo {\n"
1757                "  A = 1,\n"
1758                "  B\n"
1759                "}");
1760   verifyFormat("export /* somecomment*/ enum Foo {\n"
1761                "  A = 1,\n"
1762                "  B\n"
1763                "}");
1764   verifyFormat("enum Foo {\n"
1765                "  A = 1,  // comment\n"
1766                "  B\n"
1767                "}\n"
1768                "var x = 1;");
1769   verifyFormat("const enum Foo {\n"
1770                "  A = 1,\n"
1771                "  B\n"
1772                "}");
1773   verifyFormat("export const enum Foo {\n"
1774                "  A = 1,\n"
1775                "  B\n"
1776                "}");
1777 }
1778 
1779 TEST_F(FormatTestJS, Decorators) {
1780   verifyFormat("@A\nclass C {\n}");
1781   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
1782   verifyFormat("@A\n@B\nclass C {\n}");
1783   verifyFormat("class C {\n  @A x: string;\n}");
1784   verifyFormat("class C {\n"
1785                "  @A\n"
1786                "  private x(): string {\n"
1787                "    return 'y';\n"
1788                "  }\n"
1789                "}");
1790   verifyFormat("class C {\n"
1791                "  private x(@A x: string) {}\n"
1792                "}");
1793   verifyFormat("class X {}\n"
1794                "class Y {}");
1795   verifyFormat("class X {\n"
1796                "  @property() private isReply = false;\n"
1797                "}\n");
1798 }
1799 
1800 TEST_F(FormatTestJS, TypeAliases) {
1801   verifyFormat("type X = number;\n"
1802                "class C {}");
1803   verifyFormat("type X<Y> = Z<Y>;");
1804   verifyFormat("type X = {\n"
1805                "  y: number\n"
1806                "};\n"
1807                "class C {}");
1808   verifyFormat("export type X = {\n"
1809                "  a: string,\n"
1810                "  b?: string,\n"
1811                "};\n");
1812 }
1813 
1814 TEST_F(FormatTestJS, TypeInterfaceLineWrapping) {
1815   const FormatStyle &Style = getGoogleJSStyleWithColumns(20);
1816   verifyFormat("type LongTypeIsReallyUnreasonablyLong =\n"
1817                "    string;\n",
1818                "type LongTypeIsReallyUnreasonablyLong = string;\n", Style);
1819   verifyFormat("interface AbstractStrategyFactoryProvider {\n"
1820                "  a: number\n"
1821                "}\n",
1822                "interface AbstractStrategyFactoryProvider { a: number }\n",
1823                Style);
1824 }
1825 
1826 TEST_F(FormatTestJS, RemoveEmptyLinesInArrowFunctions) {
1827   verifyFormat("x = () => {\n"
1828                "  foo();\n"
1829                "  bar();\n"
1830                "};\n",
1831                "x = () => {\n"
1832                "\n"
1833                "  foo();\n"
1834                "  bar();\n"
1835                "\n"
1836                "};\n");
1837 }
1838 
1839 TEST_F(FormatTestJS, Modules) {
1840   verifyFormat("import SomeThing from 'some/module.js';");
1841   verifyFormat("import {X, Y} from 'some/module.js';");
1842   verifyFormat("import a, {X, Y} from 'some/module.js';");
1843   verifyFormat("import {X, Y,} from 'some/module.js';");
1844   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
1845   // Ensure Automatic Semicolon Insertion does not break on "as\n".
1846   verifyFormat("import {X as myX} from 'm';", "import {X as\n"
1847                                               " myX} from 'm';");
1848   verifyFormat("import * as lib from 'some/module.js';");
1849   verifyFormat("var x = {import: 1};\nx.import = 2;");
1850 
1851   verifyFormat("export function fn() {\n"
1852                "  return 'fn';\n"
1853                "}");
1854   verifyFormat("export function A() {}\n"
1855                "export default function B() {}\n"
1856                "export function C() {}");
1857   verifyFormat("export default () => {\n"
1858                "  let x = 1;\n"
1859                "  return x;\n"
1860                "}");
1861   verifyFormat("export const x = 12;");
1862   verifyFormat("export default class X {}");
1863   verifyFormat("export {X, Y} from 'some/module.js';");
1864   verifyFormat("export {X, Y,} from 'some/module.js';");
1865   verifyFormat("export {SomeVeryLongExport as X, "
1866                "SomeOtherVeryLongExport as Y} from 'some/module.js';");
1867   // export without 'from' is wrapped.
1868   verifyFormat("export let someRatherLongVariableName =\n"
1869                "    someSurprisinglyLongVariable + someOtherRatherLongVar;");
1870   // ... but not if from is just an identifier.
1871   verifyFormat("export {\n"
1872                "  from as from,\n"
1873                "  someSurprisinglyLongVariable as\n"
1874                "      from\n"
1875                "};",
1876                getGoogleJSStyleWithColumns(20));
1877   verifyFormat("export class C {\n"
1878                "  x: number;\n"
1879                "  y: string;\n"
1880                "}");
1881   verifyFormat("export class X {\n"
1882                "  y: number;\n"
1883                "}");
1884   verifyFormat("export abstract class X {\n"
1885                "  y: number;\n"
1886                "}");
1887   verifyFormat("export default class X {\n"
1888                "  y: number\n"
1889                "}");
1890   verifyFormat("export default function() {\n  return 1;\n}");
1891   verifyFormat("export var x = 12;");
1892   verifyFormat("class C {}\n"
1893                "export function f() {}\n"
1894                "var v;");
1895   verifyFormat("export var x: number = 12;");
1896   verifyFormat("export const y = {\n"
1897                "  a: 1,\n"
1898                "  b: 2\n"
1899                "};");
1900   verifyFormat("export enum Foo {\n"
1901                "  BAR,\n"
1902                "  // adsdasd\n"
1903                "  BAZ\n"
1904                "}");
1905   verifyFormat("export default [\n"
1906                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1907                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
1908                "];");
1909   verifyFormat("export default [];");
1910   verifyFormat("export default () => {};");
1911   verifyFormat("export default () => {\n"
1912                "  x;\n"
1913                "  x;\n"
1914                "};");
1915   verifyFormat("export interface Foo {\n"
1916                "  foo: number;\n"
1917                "}\n"
1918                "export class Bar {\n"
1919                "  blah(): string {\n"
1920                "    return this.blah;\n"
1921                "  };\n"
1922                "}");
1923 }
1924 
1925 TEST_F(FormatTestJS, ImportWrapping) {
1926   verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
1927                " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
1928                "} from 'some/module.js';");
1929   FormatStyle Style = getGoogleJSStyleWithColumns(80);
1930   Style.JavaScriptWrapImports = true;
1931   verifyFormat("import {\n"
1932                "  VeryLongImportsAreAnnoying,\n"
1933                "  VeryLongImportsAreAnnoying,\n"
1934                "  VeryLongImportsAreAnnoying,\n"
1935                "} from 'some/module.js';",
1936                Style);
1937   verifyFormat("import {\n"
1938                "  A,\n"
1939                "  A,\n"
1940                "} from 'some/module.js';",
1941                Style);
1942   verifyFormat("export {\n"
1943                "  A,\n"
1944                "  A,\n"
1945                "} from 'some/module.js';",
1946                Style);
1947   Style.ColumnLimit = 40;
1948   // Using this version of verifyFormat because test::messUp hides the issue.
1949   verifyFormat("import {\n"
1950                "  A,\n"
1951                "} from\n"
1952                "    'some/path/longer/than/column/limit/module.js';",
1953                " import  {  \n"
1954                "    A,  \n"
1955                "  }    from\n"
1956                "      'some/path/longer/than/column/limit/module.js'  ; ",
1957                Style);
1958 }
1959 
1960 TEST_F(FormatTestJS, TemplateStrings) {
1961   // Keeps any whitespace/indentation within the template string.
1962   verifyFormat("var x = `hello\n"
1963                "     ${name}\n"
1964                "  !`;",
1965                "var x    =    `hello\n"
1966                "     ${  name    }\n"
1967                "  !`;");
1968 
1969   verifyFormat("var x =\n"
1970                "    `hello ${world}` >= some();",
1971                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
1972   verifyFormat("var x = `hello ${world}` >= some();",
1973                getGoogleJSStyleWithColumns(35)); // Barely fits.
1974   verifyFormat("var x = `hellö ${wörld}` >= söme();",
1975                getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8.
1976   verifyFormat("var x = `hello\n"
1977                "  ${world}` >=\n"
1978                "    some();",
1979                "var x =\n"
1980                "    `hello\n"
1981                "  ${world}` >= some();",
1982                getGoogleJSStyleWithColumns(21)); // Barely doesn't fit.
1983   verifyFormat("var x = `hello\n"
1984                "  ${world}` >= some();",
1985                "var x =\n"
1986                "    `hello\n"
1987                "  ${world}` >= some();",
1988                getGoogleJSStyleWithColumns(22)); // Barely fits.
1989 
1990   verifyFormat("var x =\n"
1991                "    `h`;",
1992                getGoogleJSStyleWithColumns(11));
1993   verifyFormat("var x =\n    `multi\n  line`;", "var x = `multi\n  line`;",
1994                getGoogleJSStyleWithColumns(13));
1995   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1996                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
1997   // Repro for an obscure width-miscounting issue with template strings.
1998   verifyFormat(
1999       "someLongVariable =\n"
2000       "    "
2001       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;",
2002       "someLongVariable = "
2003       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;");
2004 
2005   // Make sure template strings get a proper ColumnWidth assigned, even if they
2006   // are first token in line.
2007   verifyFormat("var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2008                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
2009 
2010   // Two template strings.
2011   verifyFormat("var x = `hello` == `hello`;");
2012 
2013   // Comments in template strings.
2014   verifyFormat("var x = `//a`;\n"
2015                "var y;",
2016                "var x =\n `//a`;\n"
2017                "var y  ;");
2018   verifyFormat("var x = `/*a`;\n"
2019                "var y;",
2020                "var x =\n `/*a`;\n"
2021                "var y;");
2022   // Unterminated string literals in a template string.
2023   verifyFormat("var x = `'`;  // comment with matching quote '\n"
2024                "var y;");
2025   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
2026                "var y;");
2027   verifyFormat("it(`'aaaaaaaaaaaaaaa   `, aaaaaaaaa);",
2028                "it(`'aaaaaaaaaaaaaaa   `,   aaaaaaaaa) ;",
2029                getGoogleJSStyleWithColumns(40));
2030   // Backticks in a comment - not a template string.
2031   verifyFormat("var x = 1  // `/*a`;\n"
2032                "    ;",
2033                "var x =\n 1  // `/*a`;\n"
2034                "    ;");
2035   verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */");
2036   // Comment spans multiple template strings.
2037   verifyFormat("var x = `/*a`;\n"
2038                "var y = ` */ `;",
2039                "var x =\n `/*a`;\n"
2040                "var y =\n ` */ `;");
2041   // Escaped backtick.
2042   verifyFormat("var x = ` \\` a`;\n"
2043                "var y;",
2044                "var x = ` \\` a`;\n"
2045                "var y;");
2046   // Escaped dollar.
2047   verifyFormat("var x = ` \\${foo}`;\n");
2048 
2049   // The token stream can contain two string_literals in sequence, but that
2050   // doesn't mean that they are implicitly concatenated in JavaScript.
2051   verifyFormat("var f = `aaaa ${a ? 'a' : 'b'}`;");
2052 
2053   // Ensure that scopes are appropriately set around evaluated expressions in
2054   // template strings.
2055   verifyFormat("var f = `aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa\n"
2056                "         aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`;",
2057                "var f = `aaaaaaaaaaaaa:${aaaaaaa.  aaaaa} aaaaaaaa\n"
2058                "         aaaaaaaaaaaaa:${  aaaaaaa. aaaaa} aaaaaaaa`;");
2059   verifyFormat("var x = someFunction(`${})`)  //\n"
2060                "            .oooooooooooooooooon();");
2061   verifyFormat("var x = someFunction(`${aaaa}${\n"
2062                "    aaaaa(  //\n"
2063                "        aaaaa)})`);");
2064 }
2065 
2066 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) {
2067   verifyFormat("var f = `aaaaaaaaaaaaaaaaaa: ${\n"
2068                "    aaaaa +  //\n"
2069                "    bbbb}`;",
2070                "var f = `aaaaaaaaaaaaaaaaaa: ${aaaaa +  //\n"
2071                "                               bbbb}`;");
2072   verifyFormat("var f = `\n"
2073                "  aaaaaaaaaaaaaaaaaa: ${\n"
2074                "    aaaaa +  //\n"
2075                "    bbbb}`;",
2076                "var f  =  `\n"
2077                "  aaaaaaaaaaaaaaaaaa: ${   aaaaa  +  //\n"
2078                "                        bbbb }`;");
2079   verifyFormat("var f = `\n"
2080                "  aaaaaaaaaaaaaaaaaa: ${\n"
2081                "    someFunction(\n"
2082                "        aaaaa +  //\n"
2083                "        bbbb)}`;",
2084                "var f  =  `\n"
2085                "  aaaaaaaaaaaaaaaaaa: ${someFunction (\n"
2086                "                            aaaaa  +   //\n"
2087                "                            bbbb)}`;");
2088 
2089   // It might be preferable to wrap before "someFunction".
2090   verifyFormat("var f = `\n"
2091                "  aaaaaaaaaaaaaaaaaa: ${someFunction({\n"
2092                "  aaaa: aaaaa,\n"
2093                "  bbbb: bbbbb,\n"
2094                "})}`;",
2095                "var f  =  `\n"
2096                "  aaaaaaaaaaaaaaaaaa: ${someFunction ({\n"
2097                "                          aaaa:  aaaaa,\n"
2098                "                          bbbb:  bbbbb,\n"
2099                "                        })}`;");
2100 }
2101 
2102 TEST_F(FormatTestJS, TemplateStringASI) {
2103   verifyFormat("var x = `hello${world}`;", "var x = `hello${\n"
2104                                            "    world\n"
2105                                            "}`;");
2106 }
2107 
2108 TEST_F(FormatTestJS, NestedTemplateStrings) {
2109   verifyFormat(
2110       "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;");
2111   verifyFormat("var x = `he${({text: 'll'}.text)}o`;");
2112 
2113   // Crashed at some point.
2114   verifyFormat("}");
2115 }
2116 
2117 TEST_F(FormatTestJS, TaggedTemplateStrings) {
2118   verifyFormat("var x = html`<ul>`;");
2119   verifyFormat("yield `hello`;");
2120   verifyFormat("var f = {\n"
2121                "  param: longTagName`This is a ${\n"
2122                "                    'really'} long line`\n"
2123                "};",
2124                "var f = {param: longTagName`This is a ${'really'} long line`};",
2125                getGoogleJSStyleWithColumns(40));
2126 }
2127 
2128 TEST_F(FormatTestJS, CastSyntax) {
2129   verifyFormat("var x = <type>foo;");
2130   verifyFormat("var x = foo as type;");
2131   verifyFormat("let x = (a + b) as\n"
2132                "    LongTypeIsLong;",
2133                getGoogleJSStyleWithColumns(20));
2134   verifyFormat("foo = <Bar[]>[\n"
2135                "  1,  //\n"
2136                "  2\n"
2137                "];");
2138   verifyFormat("var x = [{x: 1} as type];");
2139   verifyFormat("x = x as [a, b];");
2140   verifyFormat("x = x as {a: string};");
2141   verifyFormat("x = x as (string);");
2142   verifyFormat("x = x! as (string);");
2143   verifyFormat("x = y! in z;");
2144   verifyFormat("var x = something.someFunction() as\n"
2145                "    something;",
2146                getGoogleJSStyleWithColumns(40));
2147 }
2148 
2149 TEST_F(FormatTestJS, TypeArguments) {
2150   verifyFormat("class X<Y> {}");
2151   verifyFormat("new X<Y>();");
2152   verifyFormat("foo<Y>(a);");
2153   verifyFormat("var x: X<Y>[];");
2154   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
2155   verifyFormat("function f(a: List<any> = null) {}");
2156   verifyFormat("function f(): List<any> {}");
2157   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
2158                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
2159   verifyFormat("function aaaaaaaaaa(\n"
2160                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
2161                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
2162                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
2163 }
2164 
2165 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
2166   verifyFormat(
2167       "function foo(check: Object):\n"
2168       "    check is {foo: string, bar: string, baz: string, foobar: string} {\n"
2169       "  return 'bar' in check;\n"
2170       "}\n");
2171 }
2172 
2173 TEST_F(FormatTestJS, OptionalTypes) {
2174   verifyFormat("function x(a?: b, c?, d?) {}");
2175   verifyFormat("class X {\n"
2176                "  y?: z;\n"
2177                "  z?;\n"
2178                "}");
2179   verifyFormat("interface X {\n"
2180                "  y?(): z;\n"
2181                "}");
2182   verifyFormat("constructor({aa}: {\n"
2183                "  aa?: string,\n"
2184                "  aaaaaaaa?: string,\n"
2185                "  aaaaaaaaaaaaaaa?: boolean,\n"
2186                "  aaaaaa?: List<string>\n"
2187                "}) {}");
2188 }
2189 
2190 TEST_F(FormatTestJS, IndexSignature) {
2191   verifyFormat("var x: {[k: string]: v};");
2192 }
2193 
2194 TEST_F(FormatTestJS, WrapAfterParen) {
2195   verifyFormat("xxxxxxxxxxx(\n"
2196                "    aaa, aaa);",
2197                getGoogleJSStyleWithColumns(20));
2198   verifyFormat("xxxxxxxxxxx(\n"
2199                "    aaa, aaa, aaa,\n"
2200                "    aaa, aaa, aaa);",
2201                getGoogleJSStyleWithColumns(20));
2202   verifyFormat("xxxxxxxxxxx(\n"
2203                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
2204                "    function(x) {\n"
2205                "      y();  //\n"
2206                "    });",
2207                getGoogleJSStyleWithColumns(40));
2208   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
2209                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2210 }
2211 
2212 TEST_F(FormatTestJS, JSDocAnnotations) {
2213   verifyFormat("/**\n"
2214                " * @exports {this.is.a.long.path.to.a.Type}\n"
2215                " */",
2216                "/**\n"
2217                " * @exports {this.is.a.long.path.to.a.Type}\n"
2218                " */",
2219                getGoogleJSStyleWithColumns(20));
2220   verifyFormat("/**\n"
2221                " * @mods {this.is.a.long.path.to.a.Type}\n"
2222                " */",
2223                "/**\n"
2224                " * @mods {this.is.a.long.path.to.a.Type}\n"
2225                " */",
2226                getGoogleJSStyleWithColumns(20));
2227   verifyFormat("/**\n"
2228                " * @mods {this.is.a.long.path.to.a.Type}\n"
2229                " */",
2230                "/**\n"
2231                " * @mods {this.is.a.long.path.to.a.Type}\n"
2232                " */",
2233                getGoogleJSStyleWithColumns(20));
2234   verifyFormat("/**\n"
2235                " * @param {canWrap\n"
2236                " *     onSpace}\n"
2237                " */",
2238                "/**\n"
2239                " * @param {canWrap onSpace}\n"
2240                " */",
2241                getGoogleJSStyleWithColumns(20));
2242   // make sure clang-format doesn't break before *any* '{'
2243   verifyFormat("/**\n"
2244                " * @lala {lala {lalala\n"
2245                " */\n",
2246                "/**\n"
2247                " * @lala {lala {lalala\n"
2248                " */\n",
2249                getGoogleJSStyleWithColumns(20));
2250   // cases where '{' is around the column limit
2251   for (int ColumnLimit = 6; ColumnLimit < 13; ++ColumnLimit) {
2252     verifyFormat("/**\n"
2253                  " * @param {type}\n"
2254                  " */",
2255                  "/**\n"
2256                  " * @param {type}\n"
2257                  " */",
2258                  getGoogleJSStyleWithColumns(ColumnLimit));
2259   }
2260   // don't break before @tags
2261   verifyFormat("/**\n"
2262                " * This\n"
2263                " * tag @param\n"
2264                " * stays.\n"
2265                " */",
2266                "/**\n"
2267                " * This tag @param stays.\n"
2268                " */",
2269                getGoogleJSStyleWithColumns(13));
2270   verifyFormat("/**\n"
2271                " * @see http://very/very/long/url/is/long\n"
2272                " */",
2273                "/**\n"
2274                " * @see http://very/very/long/url/is/long\n"
2275                " */",
2276                getGoogleJSStyleWithColumns(20));
2277   verifyFormat("/**\n"
2278                " * @param This is a\n"
2279                " *     long comment\n"
2280                " *     but no type\n"
2281                " */",
2282                "/**\n"
2283                " * @param This is a long comment but no type\n"
2284                " */",
2285                getGoogleJSStyleWithColumns(20));
2286   // Break and reindent @param line and reflow unrelated lines.
2287   EXPECT_EQ("{\n"
2288             "  /**\n"
2289             "   * long long long\n"
2290             "   * long\n"
2291             "   * @param {this.is.a.long.path.to.a.Type}\n"
2292             "   *     a\n"
2293             "   * long long long\n"
2294             "   * long long\n"
2295             "   */\n"
2296             "  function f(a) {}\n"
2297             "}",
2298             format("{\n"
2299                    "/**\n"
2300                    " * long long long long\n"
2301                    " * @param {this.is.a.long.path.to.a.Type} a\n"
2302                    " * long long long long\n"
2303                    " * long\n"
2304                    " */\n"
2305                    "  function f(a) {}\n"
2306                    "}",
2307                    getGoogleJSStyleWithColumns(20)));
2308 }
2309 
2310 TEST_F(FormatTestJS, TslintComments) {
2311   // tslint uses pragma comments that must be on their own line.
2312   verifyFormat("// Comment that needs wrapping. Comment that needs wrapping. "
2313                "Comment that needs\n"
2314                "// wrapping. Trailing line.\n"
2315                "// tslint:disable-next-line:must-be-on-own-line",
2316                "// Comment that needs wrapping. Comment that needs wrapping. "
2317                "Comment that needs wrapping.\n"
2318                "// Trailing line.\n"
2319                "// tslint:disable-next-line:must-be-on-own-line");
2320 }
2321 
2322 TEST_F(FormatTestJS, TscComments) {
2323   // As above, @ts-ignore and @ts-check comments must be on their own line.
2324   verifyFormat("// Comment that needs wrapping. Comment that needs wrapping. "
2325                "Comment that needs\n"
2326                "// wrapping. Trailing line.\n"
2327                "// @ts-ignore",
2328                "// Comment that needs wrapping. Comment that needs wrapping. "
2329                "Comment that needs wrapping.\n"
2330                "// Trailing line.\n"
2331                "// @ts-ignore");
2332   verifyFormat("// Comment that needs wrapping. Comment that needs wrapping. "
2333                "Comment that needs\n"
2334                "// wrapping. Trailing line.\n"
2335                "// @ts-check",
2336                "// Comment that needs wrapping. Comment that needs wrapping. "
2337                "Comment that needs wrapping.\n"
2338                "// Trailing line.\n"
2339                "// @ts-check");
2340 }
2341 
2342 TEST_F(FormatTestJS, RequoteStringsSingle) {
2343   verifyFormat("var x = 'foo';", "var x = \"foo\";");
2344   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";");
2345   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";");
2346   verifyFormat("var x =\n"
2347                "    'foo\\'';",
2348                // Code below is 15 chars wide, doesn't fit into the line with
2349                // the \ escape added.
2350                "var x = \"foo'\";", getGoogleJSStyleWithColumns(15));
2351   // Removes no-longer needed \ escape from ".
2352   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";");
2353   // Code below fits into 15 chars *after* removing the \ escape.
2354   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";",
2355                getGoogleJSStyleWithColumns(15));
2356   verifyFormat("// clang-format off\n"
2357                "let x = \"double\";\n"
2358                "// clang-format on\n"
2359                "let x = 'single';\n",
2360                "// clang-format off\n"
2361                "let x = \"double\";\n"
2362                "// clang-format on\n"
2363                "let x = \"single\";\n");
2364 }
2365 
2366 TEST_F(FormatTestJS, RequoteAndIndent) {
2367   verifyFormat("let x = someVeryLongFunctionThatGoesOnAndOn(\n"
2368                "    'double quoted string that needs wrapping');",
2369                "let x = someVeryLongFunctionThatGoesOnAndOn("
2370                "\"double quoted string that needs wrapping\");");
2371 
2372   verifyFormat("let x =\n"
2373                "    'foo\\'oo';\n"
2374                "let x =\n"
2375                "    'foo\\'oo';",
2376                "let x=\"foo'oo\";\n"
2377                "let x=\"foo'oo\";",
2378                getGoogleJSStyleWithColumns(15));
2379 }
2380 
2381 TEST_F(FormatTestJS, RequoteStringsDouble) {
2382   FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2383   DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double;
2384   verifyFormat("var x = \"foo\";", DoubleQuotes);
2385   verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes);
2386   verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes);
2387 }
2388 
2389 TEST_F(FormatTestJS, RequoteStringsLeave) {
2390   FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2391   LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave;
2392   verifyFormat("var x = \"foo\";", LeaveQuotes);
2393   verifyFormat("var x = 'foo';", LeaveQuotes);
2394 }
2395 
2396 TEST_F(FormatTestJS, SupportShebangLines) {
2397   verifyFormat("#!/usr/bin/env node\n"
2398                "var x = hello();",
2399                "#!/usr/bin/env node\n"
2400                "var x   =  hello();");
2401 }
2402 
2403 TEST_F(FormatTestJS, NonNullAssertionOperator) {
2404   verifyFormat("let x = foo!.bar();\n");
2405   verifyFormat("let x = foo ? bar! : baz;\n");
2406   verifyFormat("let x = !foo;\n");
2407   verifyFormat("if (!+a) {\n}");
2408   verifyFormat("let x = foo[0]!;\n");
2409   verifyFormat("let x = (foo)!;\n");
2410   verifyFormat("let x = x(foo!);\n");
2411   verifyFormat("a.aaaaaa(a.a!).then(\n"
2412                "    x => x(x));\n",
2413                getGoogleJSStyleWithColumns(20));
2414   verifyFormat("let x = foo! - 1;\n");
2415   verifyFormat("let x = {foo: 1}!;\n");
2416   verifyFormat("let x = hello.foo()!\n"
2417                "            .foo()!\n"
2418                "            .foo()!\n"
2419                "            .foo()!;\n",
2420                getGoogleJSStyleWithColumns(20));
2421   verifyFormat("let x = namespace!;\n");
2422   verifyFormat("return !!x;\n");
2423 }
2424 
2425 TEST_F(FormatTestJS, CppKeywords) {
2426   // Make sure we don't mess stuff up because of C++ keywords.
2427   verifyFormat("return operator && (aa);");
2428   // .. or QT ones.
2429   verifyFormat("const slots: Slot[];");
2430   // use the "!" assertion operator to validate that clang-format understands
2431   // these C++ keywords aren't keywords in JS/TS.
2432   verifyFormat("auto!;");
2433   verifyFormat("char!;");
2434   verifyFormat("concept!;");
2435   verifyFormat("double!;");
2436   verifyFormat("extern!;");
2437   verifyFormat("float!;");
2438   verifyFormat("inline!;");
2439   verifyFormat("int!;");
2440   verifyFormat("long!;");
2441   verifyFormat("register!;");
2442   verifyFormat("restrict!;");
2443   verifyFormat("sizeof!;");
2444   verifyFormat("struct!;");
2445   verifyFormat("typedef!;");
2446   verifyFormat("union!;");
2447   verifyFormat("unsigned!;");
2448   verifyFormat("volatile!;");
2449   verifyFormat("_Alignas!;");
2450   verifyFormat("_Alignof!;");
2451   verifyFormat("_Atomic!;");
2452   verifyFormat("_Bool!;");
2453   verifyFormat("_Complex!;");
2454   verifyFormat("_Generic!;");
2455   verifyFormat("_Imaginary!;");
2456   verifyFormat("_Noreturn!;");
2457   verifyFormat("_Static_assert!;");
2458   verifyFormat("_Thread_local!;");
2459   verifyFormat("__func__!;");
2460   verifyFormat("__objc_yes!;");
2461   verifyFormat("__objc_no!;");
2462   verifyFormat("asm!;");
2463   verifyFormat("bool!;");
2464   verifyFormat("const_cast!;");
2465   verifyFormat("dynamic_cast!;");
2466   verifyFormat("explicit!;");
2467   verifyFormat("friend!;");
2468   verifyFormat("mutable!;");
2469   verifyFormat("operator!;");
2470   verifyFormat("reinterpret_cast!;");
2471   verifyFormat("static_cast!;");
2472   verifyFormat("template!;");
2473   verifyFormat("typename!;");
2474   verifyFormat("typeid!;");
2475   verifyFormat("using!;");
2476   verifyFormat("virtual!;");
2477   verifyFormat("wchar_t!;");
2478 
2479   // Positive tests:
2480   verifyFormat("x.type!;");
2481   verifyFormat("x.get!;");
2482   verifyFormat("x.set!;");
2483 }
2484 
2485 TEST_F(FormatTestJS, NullPropagatingOperator) {
2486   verifyFormat("let x = foo?.bar?.baz();\n");
2487   verifyFormat("let x = foo?.(foo);\n");
2488   verifyFormat("let x = foo?.['arr'];\n");
2489 }
2490 
2491 TEST_F(FormatTestJS, NullishCoalescingOperator) {
2492   verifyFormat("const val = something ?? 'some other default';\n");
2493   verifyFormat(
2494       "const val = something ?? otherDefault ??\n"
2495       "    evenMore ?? evenMore;\n",
2496       "const val = something ?? otherDefault ?? evenMore ?? evenMore;\n",
2497       getGoogleJSStyleWithColumns(40));
2498 }
2499 
2500 TEST_F(FormatTestJS, AssignmentOperators) {
2501   verifyFormat("a &&= b;\n");
2502   verifyFormat("a ||= b;\n");
2503   // NB: need to split ? ?= to avoid it being interpreted by C++ as a trigraph
2504   // for #.
2505   verifyFormat("a ?"
2506                "?= b;\n");
2507 }
2508 
2509 TEST_F(FormatTestJS, Conditional) {
2510   verifyFormat("y = x ? 1 : 2;");
2511   verifyFormat("x ? 1 : 2;");
2512   verifyFormat("class Foo {\n"
2513                "  field = true ? 1 : 2;\n"
2514                "  method(a = true ? 1 : 2) {}\n"
2515                "}");
2516 }
2517 
2518 TEST_F(FormatTestJS, ImportComments) {
2519   verifyFormat("import {x} from 'x';  // from some location",
2520                getGoogleJSStyleWithColumns(25));
2521   verifyFormat("// taze: x from 'location'", getGoogleJSStyleWithColumns(10));
2522   verifyFormat("/// <reference path=\"some/location\" />",
2523                getGoogleJSStyleWithColumns(10));
2524 }
2525 
2526 TEST_F(FormatTestJS, Exponentiation) {
2527   verifyFormat("squared = x ** 2;");
2528   verifyFormat("squared **= 2;");
2529 }
2530 
2531 TEST_F(FormatTestJS, NestedLiterals) {
2532   FormatStyle FourSpaces = getGoogleJSStyleWithColumns(15);
2533   FourSpaces.IndentWidth = 4;
2534   verifyFormat("var l = [\n"
2535                "    [\n"
2536                "        1,\n"
2537                "    ],\n"
2538                "];",
2539                FourSpaces);
2540   verifyFormat("var l = [\n"
2541                "    {\n"
2542                "        1: 1,\n"
2543                "    },\n"
2544                "];",
2545                FourSpaces);
2546   verifyFormat("someFunction(\n"
2547                "    p1,\n"
2548                "    [\n"
2549                "        1,\n"
2550                "    ],\n"
2551                ");",
2552                FourSpaces);
2553   verifyFormat("someFunction(\n"
2554                "    p1,\n"
2555                "    {\n"
2556                "        1: 1,\n"
2557                "    },\n"
2558                ");",
2559                FourSpaces);
2560   verifyFormat("var o = {\n"
2561                "    1: 1,\n"
2562                "    2: {\n"
2563                "        3: 3,\n"
2564                "    },\n"
2565                "};",
2566                FourSpaces);
2567   verifyFormat("var o = {\n"
2568                "    1: 1,\n"
2569                "    2: [\n"
2570                "        3,\n"
2571                "    ],\n"
2572                "};",
2573                FourSpaces);
2574 }
2575 
2576 TEST_F(FormatTestJS, BackslashesInComments) {
2577   verifyFormat("// hello \\\n"
2578                "if (x) foo();\n",
2579                "// hello \\\n"
2580                "     if ( x) \n"
2581                "   foo();\n");
2582   verifyFormat("/* ignore \\\n"
2583                " */\n"
2584                "if (x) foo();\n",
2585                "/* ignore \\\n"
2586                " */\n"
2587                " if (  x) foo();\n");
2588   verifyFormat("// st \\ art\\\n"
2589                "// comment"
2590                "// continue \\\n"
2591                "formatMe();\n",
2592                "// st \\ art\\\n"
2593                "// comment"
2594                "// continue \\\n"
2595                "formatMe( );\n");
2596 }
2597 
2598 TEST_F(FormatTestJS, AddsLastLinePenaltyIfEndingIsBroken) {
2599   EXPECT_EQ(
2600       "a = function() {\n"
2601       "  b = function() {\n"
2602       "    this.aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa] = aaaa.aaaaaa ?\n"
2603       "        aaaa.aaaaaa : /** @type "
2604       "{aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaaaaaaaa} */\n"
2605       "        (aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaa);\n"
2606       "  };\n"
2607       "};",
2608       format("a = function() {\n"
2609              "  b = function() {\n"
2610              "    this.aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa] = aaaa.aaaaaa ? "
2611              "aaaa.aaaaaa : /** @type "
2612              "{aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaaaaaaaa} */\n"
2613              "        (aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaa);\n"
2614              "  };\n"
2615              "};"));
2616 }
2617 
2618 TEST_F(FormatTestJS, ParameterNamingComment) {
2619   verifyFormat("callFoo(/*spaceAfterParameterNamingComment=*/ 1);");
2620 }
2621 
2622 TEST_F(FormatTestJS, ConditionalTypes) {
2623   // Formatting below is not necessarily intentional, this just ensures that
2624   // clang-format does not break the code.
2625   verifyFormat( // wrap
2626       "type UnionToIntersection<U> =\n"
2627       "    (U extends any ? (k: U) => void :\n"
2628       "                     never) extends((k: infer I) => void) ? I : never;");
2629 }
2630 
2631 TEST_F(FormatTestJS, SupportPrivateFieldsAndMethods) {
2632   verifyFormat("class Example {\n"
2633                "  pub = 1;\n"
2634                "  #priv = 2;\n"
2635                "  static pub2 = 'foo';\n"
2636                "  static #priv2 = 'bar';\n"
2637                "  method() {\n"
2638                "    this.#priv = 5;\n"
2639                "  }\n"
2640                "  static staticMethod() {\n"
2641                "    switch (this.#priv) {\n"
2642                "      case '1':\n"
2643                "        #priv = 3;\n"
2644                "        break;\n"
2645                "    }\n"
2646                "  }\n"
2647                "  #privateMethod() {\n"
2648                "    this.#privateMethod();  // infinite loop\n"
2649                "  }\n"
2650                "  static #staticPrivateMethod() {}\n");
2651 }
2652 
2653 TEST_F(FormatTestJS, DeclaredFields) {
2654   verifyFormat("class Example {\n"
2655                "  declare pub: string;\n"
2656                "  declare private priv: string;\n"
2657                "}\n");
2658 }
2659 
2660 TEST_F(FormatTestJS, NoBreakAfterAsserts) {
2661   verifyFormat(
2662       "interface Assertable<State extends {}> {\n"
2663       "  assert<ExportedState extends {}, DependencyState extends State = "
2664       "State>(\n"
2665       "      callback: Callback<ExportedState, DependencyState>):\n"
2666       "      asserts this is ExtendedState<DependencyState&ExportedState>;\n"
2667       "}\n",
2668       "interface Assertable<State extends {}> {\n"
2669       "  assert<ExportedState extends {}, DependencyState extends State = "
2670       "State>(callback: Callback<ExportedState, DependencyState>): asserts "
2671       "this is ExtendedState<DependencyState&ExportedState>;\n"
2672       "}\n");
2673 }
2674 
2675 } // namespace format
2676 } // end namespace clang
2677