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, GeneratorFunctions) {
705   verifyFormat("function* f() {\n"
706                "  let x = 1;\n"
707                "  yield x;\n"
708                "  yield* something();\n"
709                "  yield [1, 2];\n"
710                "  yield {a: 1};\n"
711                "}");
712   verifyFormat("function*\n"
713                "    f() {\n"
714                "}",
715                getGoogleJSStyleWithColumns(8));
716   verifyFormat("export function* f() {\n"
717                "  yield 1;\n"
718                "}\n");
719   verifyFormat("class X {\n"
720                "  * generatorMethod() {\n"
721                "    yield x;\n"
722                "  }\n"
723                "}");
724   verifyFormat("var x = {\n"
725                "  a: function*() {\n"
726                "    //\n"
727                "  }\n"
728                "}\n");
729 }
730 
731 TEST_F(FormatTestJS, AsyncFunctions) {
732   verifyFormat("async function f() {\n"
733                "  let x = 1;\n"
734                "  return fetch(x);\n"
735                "}");
736   verifyFormat("async function f() {\n"
737                "  return 1;\n"
738                "}\n"
739                "\n"
740                "function a() {\n"
741                "  return 1;\n"
742                "}\n",
743                "  async   function f() {\n"
744                "   return 1;\n"
745                "}\n"
746                "\n"
747                "   function a() {\n"
748                "  return   1;\n"
749                "}  \n");
750   // clang-format must not insert breaks between async and function, otherwise
751   // automatic semicolon insertion may trigger (in particular in a class body).
752   verifyFormat("async function\n"
753                "hello(\n"
754                "    myparamnameiswaytooloooong) {\n"
755                "}",
756                "async function hello(myparamnameiswaytooloooong) {}",
757                getGoogleJSStyleWithColumns(10));
758   verifyFormat("class C {\n"
759                "  async hello(\n"
760                "      myparamnameiswaytooloooong) {\n"
761                "  }\n"
762                "}",
763                "class C {\n"
764                "  async hello(myparamnameiswaytooloooong) {} }",
765                getGoogleJSStyleWithColumns(10));
766   verifyFormat("async function* f() {\n"
767                "  yield fetch(x);\n"
768                "}");
769   verifyFormat("export async function f() {\n"
770                "  return fetch(x);\n"
771                "}");
772   verifyFormat("let x = async () => f();");
773   verifyFormat("let x = async function() {\n"
774                "  f();\n"
775                "};");
776   verifyFormat("let x = async();");
777   verifyFormat("class X {\n"
778                "  async asyncMethod() {\n"
779                "    return fetch(1);\n"
780                "  }\n"
781                "}");
782   verifyFormat("function initialize() {\n"
783                "  // Comment.\n"
784                "  return async.then();\n"
785                "}\n");
786   verifyFormat("for await (const x of y) {\n"
787                "  console.log(x);\n"
788                "}\n");
789   verifyFormat("function asyncLoop() {\n"
790                "  for await (const x of y) {\n"
791                "    console.log(x);\n"
792                "  }\n"
793                "}\n");
794 }
795 
796 TEST_F(FormatTestJS, FunctionParametersTrailingComma) {
797   verifyFormat("function trailingComma(\n"
798                "    p1,\n"
799                "    p2,\n"
800                "    p3,\n"
801                ") {\n"
802                "  a;  //\n"
803                "}\n",
804                "function trailingComma(p1, p2, p3,) {\n"
805                "  a;  //\n"
806                "}\n");
807   verifyFormat("trailingComma(\n"
808                "    p1,\n"
809                "    p2,\n"
810                "    p3,\n"
811                ");\n",
812                "trailingComma(p1, p2, p3,);\n");
813   verifyFormat("trailingComma(\n"
814                "    p1  // hello\n"
815                ");\n",
816                "trailingComma(p1 // hello\n"
817                ");\n");
818 }
819 
820 TEST_F(FormatTestJS, ArrayLiterals) {
821   verifyFormat("var aaaaa: List<SomeThing> =\n"
822                "    [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];");
823   verifyFormat("return [\n"
824                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
825                "  ccccccccccccccccccccccccccc\n"
826                "];");
827   verifyFormat("return [\n"
828                "  aaaa().bbbbbbbb('A'),\n"
829                "  aaaa().bbbbbbbb('B'),\n"
830                "  aaaa().bbbbbbbb('C'),\n"
831                "];");
832   verifyFormat("var someVariable = SomeFunction([\n"
833                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
834                "  ccccccccccccccccccccccccccc\n"
835                "]);");
836   verifyFormat("var someVariable = SomeFunction([\n"
837                "  [aaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbb],\n"
838                "]);",
839                getGoogleJSStyleWithColumns(51));
840   verifyFormat("var someVariable = SomeFunction(aaaa, [\n"
841                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
842                "  ccccccccccccccccccccccccccc\n"
843                "]);");
844   verifyFormat("var someVariable = SomeFunction(\n"
845                "    aaaa,\n"
846                "    [\n"
847                "      aaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
848                "      cccccccccccccccccccccccccc\n"
849                "    ],\n"
850                "    aaaa);");
851   verifyFormat("var aaaa = aaaaa ||  // wrap\n"
852                "    [];");
853 
854   verifyFormat("someFunction([], {a: a});");
855 
856   verifyFormat("var string = [\n"
857                "  'aaaaaa',\n"
858                "  'bbbbbb',\n"
859                "].join('+');");
860 }
861 
862 TEST_F(FormatTestJS, ColumnLayoutForArrayLiterals) {
863   verifyFormat("var array = [\n"
864                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
865                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
866                "];");
867   verifyFormat("var array = someFunction([\n"
868                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
869                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
870                "]);");
871 }
872 
873 TEST_F(FormatTestJS, TrailingCommaInsertion) {
874   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
875   Style.InsertTrailingCommas = FormatStyle::TCS_Wrapped;
876   // Insert comma in wrapped array.
877   verifyFormat("const x = [\n"
878                "  1,  //\n"
879                "  2,\n"
880                "];",
881                "const x = [\n"
882                "  1,  //\n"
883                "  2];",
884                Style);
885   // Insert comma in newly wrapped array.
886   Style.ColumnLimit = 30;
887   verifyFormat("const x = [\n"
888                "  aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
889                "];",
890                "const x = [aaaaaaaaaaaaaaaaaaaaaaaaa];", Style);
891   // Do not insert trailing commas if they'd exceed the colum limit
892   verifyFormat("const x = [\n"
893                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
894                "];",
895                "const x = [aaaaaaaaaaaaaaaaaaaaaaaaaaaa];", Style);
896   // Object literals.
897   verifyFormat("const x = {\n"
898                "  a: aaaaaaaaaaaaaaaaa,\n"
899                "};",
900                "const x = {a: aaaaaaaaaaaaaaaaa};", Style);
901   verifyFormat("const x = {\n"
902                "  a: aaaaaaaaaaaaaaaaaaaaaaaaa\n"
903                "};",
904                "const x = {a: aaaaaaaaaaaaaaaaaaaaaaaaa};", Style);
905   // Object literal types.
906   verifyFormat("let x: {\n"
907                "  a: aaaaaaaaaaaaaaaaaaaaa,\n"
908                "};",
909                "let x: {a: aaaaaaaaaaaaaaaaaaaaa};", Style);
910 }
911 
912 TEST_F(FormatTestJS, FunctionLiterals) {
913   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
914   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
915   verifyFormat("doFoo(function() {});");
916   verifyFormat("doFoo(function() { return 1; });", Style);
917   verifyFormat("var func = function() {\n"
918                "  return 1;\n"
919                "};");
920   verifyFormat("var func =  //\n"
921                "    function() {\n"
922                "  return 1;\n"
923                "};");
924   verifyFormat("return {\n"
925                "  body: {\n"
926                "    setAttribute: function(key, val) { this[key] = val; },\n"
927                "    getAttribute: function(key) { return this[key]; },\n"
928                "    style: {direction: ''}\n"
929                "  }\n"
930                "};",
931                Style);
932   verifyFormat("abc = xyz ? function() {\n"
933                "  return 1;\n"
934                "} : function() {\n"
935                "  return -1;\n"
936                "};");
937 
938   verifyFormat("var closure = goog.bind(\n"
939                "    function() {  // comment\n"
940                "      foo();\n"
941                "      bar();\n"
942                "    },\n"
943                "    this, arg1IsReallyLongAndNeedsLineBreaks,\n"
944                "    arg3IsReallyLongAndNeedsLineBreaks);");
945   verifyFormat("var closure = goog.bind(function() {  // comment\n"
946                "  foo();\n"
947                "  bar();\n"
948                "}, this);");
949   verifyFormat("return {\n"
950                "  a: 'E',\n"
951                "  b: function() {\n"
952                "    return function() {\n"
953                "      f();  //\n"
954                "    };\n"
955                "  }\n"
956                "};");
957   verifyFormat("{\n"
958                "  var someVariable = function(x) {\n"
959                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
960                "  };\n"
961                "}");
962   verifyFormat("someLooooooooongFunction(\n"
963                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
964                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
965                "    function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
966                "      // code\n"
967                "    });");
968 
969   verifyFormat("return {\n"
970                "  a: function SomeFunction() {\n"
971                "    // ...\n"
972                "    return 1;\n"
973                "  }\n"
974                "};");
975   verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
976                "    .then(goog.bind(function(aaaaaaaaaaa) {\n"
977                "      someFunction();\n"
978                "      someFunction();\n"
979                "    }, this), aaaaaaaaaaaaaaaaa);");
980 
981   verifyFormat("someFunction(goog.bind(function() {\n"
982                "  doSomething();\n"
983                "  doSomething();\n"
984                "}, this), goog.bind(function() {\n"
985                "  doSomething();\n"
986                "  doSomething();\n"
987                "}, this));");
988 
989   verifyFormat("SomeFunction(function() {\n"
990                "  foo();\n"
991                "  bar();\n"
992                "}.bind(this));");
993 
994   verifyFormat("SomeFunction((function() {\n"
995                "               foo();\n"
996                "               bar();\n"
997                "             }).bind(this));");
998 
999   // FIXME: This is bad, we should be wrapping before "function() {".
1000   verifyFormat("someFunction(function() {\n"
1001                "  doSomething();  // break\n"
1002                "})\n"
1003                "    .doSomethingElse(\n"
1004                "        // break\n"
1005                "    );");
1006 
1007   Style.ColumnLimit = 33;
1008   verifyFormat("f({a: function() { return 1; }});", Style);
1009   Style.ColumnLimit = 32;
1010   verifyFormat("f({\n"
1011                "  a: function() { return 1; }\n"
1012                "});",
1013                Style);
1014 }
1015 
1016 TEST_F(FormatTestJS, DontWrapEmptyLiterals) {
1017   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
1018                "    .and.returnValue(Observable.of([]));");
1019   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
1020                "    .and.returnValue(Observable.of({}));");
1021   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
1022                "    .and.returnValue(Observable.of(()));");
1023 }
1024 
1025 TEST_F(FormatTestJS, InliningFunctionLiterals) {
1026   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
1027   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
1028   verifyFormat("var func = function() {\n"
1029                "  return 1;\n"
1030                "};",
1031                Style);
1032   verifyFormat("var func = doSomething(function() { return 1; });", Style);
1033   verifyFormat("var outer = function() {\n"
1034                "  var inner = function() { return 1; }\n"
1035                "};",
1036                Style);
1037   verifyFormat("function outer1(a, b) {\n"
1038                "  function inner1(a, b) { return a; }\n"
1039                "}",
1040                Style);
1041 
1042   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1043   verifyFormat("var func = function() { return 1; };", Style);
1044   verifyFormat("var func = doSomething(function() { return 1; });", Style);
1045   verifyFormat(
1046       "var outer = function() { var inner = function() { return 1; } };",
1047       Style);
1048   verifyFormat("function outer1(a, b) {\n"
1049                "  function inner1(a, b) { return a; }\n"
1050                "}",
1051                Style);
1052 
1053   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
1054   verifyFormat("var func = function() {\n"
1055                "  return 1;\n"
1056                "};",
1057                Style);
1058   verifyFormat("var func = doSomething(function() {\n"
1059                "  return 1;\n"
1060                "});",
1061                Style);
1062   verifyFormat("var outer = function() {\n"
1063                "  var inner = function() {\n"
1064                "    return 1;\n"
1065                "  }\n"
1066                "};",
1067                Style);
1068   verifyFormat("function outer1(a, b) {\n"
1069                "  function inner1(a, b) {\n"
1070                "    return a;\n"
1071                "  }\n"
1072                "}",
1073                Style);
1074 
1075   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1076   verifyFormat("var func = function() {\n"
1077                "  return 1;\n"
1078                "};",
1079                Style);
1080 }
1081 
1082 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
1083   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
1084   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1085   verifyFormat("promise.then(\n"
1086                "    function success() {\n"
1087                "      doFoo();\n"
1088                "      doBar();\n"
1089                "    },\n"
1090                "    function error() {\n"
1091                "      doFoo();\n"
1092                "      doBaz();\n"
1093                "    },\n"
1094                "    []);\n");
1095   verifyFormat("promise.then(\n"
1096                "    function success() {\n"
1097                "      doFoo();\n"
1098                "      doBar();\n"
1099                "    },\n"
1100                "    [],\n"
1101                "    function error() {\n"
1102                "      doFoo();\n"
1103                "      doBaz();\n"
1104                "    });\n");
1105   verifyFormat("promise.then(\n"
1106                "    [],\n"
1107                "    function success() {\n"
1108                "      doFoo();\n"
1109                "      doBar();\n"
1110                "    },\n"
1111                "    function error() {\n"
1112                "      doFoo();\n"
1113                "      doBaz();\n"
1114                "    });\n");
1115 
1116   verifyFormat("getSomeLongPromise()\n"
1117                "    .then(function(value) { body(); })\n"
1118                "    .thenCatch(function(error) {\n"
1119                "      body();\n"
1120                "      body();\n"
1121                "    });",
1122                Style);
1123   verifyFormat("getSomeLongPromise()\n"
1124                "    .then(function(value) {\n"
1125                "      body();\n"
1126                "      body();\n"
1127                "    })\n"
1128                "    .thenCatch(function(error) {\n"
1129                "      body();\n"
1130                "      body();\n"
1131                "    });");
1132 
1133   verifyFormat("getSomeLongPromise()\n"
1134                "    .then(function(value) { body(); })\n"
1135                "    .thenCatch(function(error) { body(); });",
1136                Style);
1137 
1138   verifyFormat("return [aaaaaaaaaaaaaaaaaaaaaa]\n"
1139                "    .aaaaaaa(function() {\n"
1140                "      //\n"
1141                "    })\n"
1142                "    .bbbbbb();");
1143 }
1144 
1145 TEST_F(FormatTestJS, ArrowFunctions) {
1146   verifyFormat("var x = (a) => {\n"
1147                "  x;\n"
1148                "  return a;\n"
1149                "};\n");
1150   verifyFormat("var x = (a) => {\n"
1151                "  function y() {\n"
1152                "    return 42;\n"
1153                "  }\n"
1154                "  return a;\n"
1155                "};");
1156   verifyFormat("var x = (a: type): {some: type} => {\n"
1157                "  y;\n"
1158                "  return a;\n"
1159                "};");
1160   verifyFormat("var x = (a) => a;");
1161   verifyFormat("return () => [];");
1162   verifyFormat("var aaaaaaaaaaaaaaaaaaaa = {\n"
1163                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
1164                "      (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1165                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) =>\n"
1166                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1167                "};");
1168   verifyFormat("var a = a.aaaaaaa(\n"
1169                "    (a: a) => aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) &&\n"
1170                "        aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
1171   verifyFormat("var a = a.aaaaaaa(\n"
1172                "    (a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) ?\n"
1173                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb) :\n"
1174                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
1175 
1176   // FIXME: This is bad, we should be wrapping before "() => {".
1177   verifyFormat("someFunction(() => {\n"
1178                "  doSomething();  // break\n"
1179                "})\n"
1180                "    .doSomethingElse(\n"
1181                "        // break\n"
1182                "    );");
1183   verifyFormat("const f = (x: string|null): string|null => {\n"
1184                "  y;\n"
1185                "  return x;\n"
1186                "}\n");
1187 }
1188 
1189 TEST_F(FormatTestJS, ArrowFunctionStyle) {
1190   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
1191   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
1192   verifyFormat("const arr = () => { x; };", Style);
1193   verifyFormat("const arrInlineAll = () => {};", Style);
1194   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
1195   verifyFormat("const arr = () => {\n"
1196                "  x;\n"
1197                "};",
1198                Style);
1199   verifyFormat("const arrInlineNone = () => {\n"
1200                "};",
1201                Style);
1202   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
1203   verifyFormat("const arr = () => {\n"
1204                "  x;\n"
1205                "};",
1206                Style);
1207   verifyFormat("const arrInlineEmpty = () => {};", Style);
1208   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
1209   verifyFormat("const arr = () => {\n"
1210                "  x;\n"
1211                "};",
1212                Style);
1213   verifyFormat("foo(() => {});", Style);
1214   verifyFormat("const arrInlineInline = () => {};", Style);
1215 }
1216 
1217 TEST_F(FormatTestJS, ReturnStatements) {
1218   verifyFormat("function() {\n"
1219                "  return [hello, world];\n"
1220                "}");
1221 }
1222 
1223 TEST_F(FormatTestJS, ForLoops) {
1224   verifyFormat("for (var i in [2, 3]) {\n"
1225                "}");
1226   verifyFormat("for (var i of [2, 3]) {\n"
1227                "}");
1228   verifyFormat("for (let {a, b} of x) {\n"
1229                "}");
1230   verifyFormat("for (let {a, b} of [x]) {\n"
1231                "}");
1232   verifyFormat("for (let [a, b] of [x]) {\n"
1233                "}");
1234   verifyFormat("for (let {a, b} in x) {\n"
1235                "}");
1236 }
1237 
1238 TEST_F(FormatTestJS, WrapRespectsAutomaticSemicolonInsertion) {
1239   // The following statements must not wrap, as otherwise the program meaning
1240   // would change due to automatic semicolon insertion.
1241   // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
1242   verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10));
1243   verifyFormat("yield aaaaa;", getGoogleJSStyleWithColumns(10));
1244   verifyFormat("return /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10));
1245   verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10));
1246   verifyFormat("continue /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10));
1247   verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10));
1248   verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
1249   verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
1250   verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
1251   verifyFormat("return [\n"
1252                "  aaa\n"
1253                "];",
1254                getGoogleJSStyleWithColumns(12));
1255   verifyFormat("class X {\n"
1256                "  readonly ratherLongField =\n"
1257                "      1;\n"
1258                "}",
1259                "class X {\n"
1260                "  readonly ratherLongField = 1;\n"
1261                "}",
1262                getGoogleJSStyleWithColumns(20));
1263   verifyFormat("const x = (5 + 9)\n"
1264                "const y = 3\n",
1265                "const x = (   5 +    9)\n"
1266                "const y = 3\n");
1267   // Ideally the foo() bit should be indented relative to the async function().
1268   verifyFormat("async function\n"
1269                "foo() {}",
1270                getGoogleJSStyleWithColumns(10));
1271   verifyFormat("await theReckoning;", getGoogleJSStyleWithColumns(10));
1272   verifyFormat("some['a']['b']", getGoogleJSStyleWithColumns(10));
1273   verifyFormat("x = (a['a']\n"
1274                "      ['b']);",
1275                getGoogleJSStyleWithColumns(10));
1276   verifyFormat("function f() {\n"
1277                "  return foo.bar(\n"
1278                "      (param): param is {\n"
1279                "        a: SomeType\n"
1280                "      }&ABC => 1)\n"
1281                "}",
1282                getGoogleJSStyleWithColumns(25));
1283 }
1284 
1285 TEST_F(FormatTestJS, AddsIsTheDictKeyOnNewline) {
1286   // Do not confuse is, the dict key with is, the type matcher. Put is, the dict
1287   // key, on a newline.
1288   verifyFormat("Polymer({\n"
1289                "  is: '',  //\n"
1290                "  rest: 1\n"
1291                "});",
1292                getGoogleJSStyleWithColumns(20));
1293 }
1294 
1295 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
1296   verifyFormat("a\n"
1297                "b;",
1298                " a \n"
1299                " b ;");
1300   verifyFormat("a()\n"
1301                "b;",
1302                " a ()\n"
1303                " b ;");
1304   verifyFormat("a[b]\n"
1305                "c;",
1306                "a [b]\n"
1307                "c ;");
1308   verifyFormat("1\n"
1309                "a;",
1310                "1 \n"
1311                "a ;");
1312   verifyFormat("a\n"
1313                "1;",
1314                "a \n"
1315                "1 ;");
1316   verifyFormat("a\n"
1317                "'x';",
1318                "a \n"
1319                " 'x';");
1320   verifyFormat("a++\n"
1321                "b;",
1322                "a ++\n"
1323                "b ;");
1324   verifyFormat("a\n"
1325                "!b && c;",
1326                "a \n"
1327                " ! b && c;");
1328   verifyFormat("a\n"
1329                "if (1) f();",
1330                " a\n"
1331                " if (1) f();");
1332   verifyFormat("a\n"
1333                "class X {}",
1334                " a\n"
1335                " class X {}");
1336   verifyFormat("var a", "var\n"
1337                         "a");
1338   verifyFormat("x instanceof String", "x\n"
1339                                       "instanceof\n"
1340                                       "String");
1341   verifyFormat("function f(@Foo bar) {}", "function f(@Foo\n"
1342                                           "  bar) {}");
1343   verifyFormat("function f(@Foo(Param) bar) {}", "function f(@Foo(Param)\n"
1344                                                  "  bar) {}");
1345   verifyFormat("a = true\n"
1346                "return 1",
1347                "a = true\n"
1348                "  return   1");
1349   verifyFormat("a = 's'\n"
1350                "return 1",
1351                "a = 's'\n"
1352                "  return   1");
1353   verifyFormat("a = null\n"
1354                "return 1",
1355                "a = null\n"
1356                "  return   1");
1357   // Below "class Y {}" should ideally be on its own line.
1358   verifyFormat("x = {\n"
1359                "  a: 1\n"
1360                "} class Y {}",
1361                "  x  =  {a  : 1}\n"
1362                "   class  Y {  }");
1363   verifyFormat("if (x) {\n"
1364                "}\n"
1365                "return 1",
1366                "if (x) {}\n"
1367                " return   1");
1368   verifyFormat("if (x) {\n"
1369                "}\n"
1370                "class X {}",
1371                "if (x) {}\n"
1372                " class X {}");
1373 }
1374 
1375 TEST_F(FormatTestJS, ImportExportASI) {
1376   verifyFormat("import {x} from 'y'\n"
1377                "export function z() {}",
1378                "import   {x} from 'y'\n"
1379                "  export function z() {}");
1380   // Below "class Y {}" should ideally be on its own line.
1381   verifyFormat("export {x} class Y {}", "  export {x}\n"
1382                                         "  class  Y {\n}");
1383   verifyFormat("if (x) {\n"
1384                "}\n"
1385                "export class Y {}",
1386                "if ( x ) { }\n"
1387                " export class Y {}");
1388 }
1389 
1390 TEST_F(FormatTestJS, ClosureStyleCasts) {
1391   verifyFormat("var x = /** @type {foo} */ (bar);");
1392 }
1393 
1394 TEST_F(FormatTestJS, TryCatch) {
1395   verifyFormat("try {\n"
1396                "  f();\n"
1397                "} catch (e) {\n"
1398                "  g();\n"
1399                "} finally {\n"
1400                "  h();\n"
1401                "}");
1402 
1403   // But, of course, "catch" is a perfectly fine function name in JavaScript.
1404   verifyFormat("someObject.catch();");
1405   verifyFormat("someObject.new();");
1406 }
1407 
1408 TEST_F(FormatTestJS, StringLiteralConcatenation) {
1409   verifyFormat("var literal = 'hello ' +\n"
1410                "    'world';");
1411 }
1412 
1413 TEST_F(FormatTestJS, RegexLiteralClassification) {
1414   // Regex literals.
1415   verifyFormat("var regex = /abc/;");
1416   verifyFormat("f(/abc/);");
1417   verifyFormat("f(abc, /abc/);");
1418   verifyFormat("some_map[/abc/];");
1419   verifyFormat("var x = a ? /abc/ : /abc/;");
1420   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
1421   verifyFormat("var x = !/abc/.test(y);");
1422   verifyFormat("var x = foo()! / 10;");
1423   verifyFormat("var x = a && /abc/.test(y);");
1424   verifyFormat("var x = a || /abc/.test(y);");
1425   verifyFormat("var x = a + /abc/.search(y);");
1426   verifyFormat("/abc/.search(y);");
1427   verifyFormat("var regexs = {/abc/, /abc/};");
1428   verifyFormat("return /abc/;");
1429 
1430   // Not regex literals.
1431   verifyFormat("var a = a / 2 + b / 3;");
1432   verifyFormat("var a = a++ / 2;");
1433   // Prefix unary can operate on regex literals, not that it makes sense.
1434   verifyFormat("var a = ++/a/;");
1435 
1436   // This is a known issue, regular expressions are incorrectly detected if
1437   // directly following a closing parenthesis.
1438   verifyFormat("if (foo) / bar /.exec(baz);");
1439 }
1440 
1441 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
1442   verifyFormat("var regex = /=/;");
1443   verifyFormat("var regex = /a*/;");
1444   verifyFormat("var regex = /a+/;");
1445   verifyFormat("var regex = /a?/;");
1446   verifyFormat("var regex = /.a./;");
1447   verifyFormat("var regex = /a\\*/;");
1448   verifyFormat("var regex = /^a$/;");
1449   verifyFormat("var regex = /\\/a/;");
1450   verifyFormat("var regex = /(?:x)/;");
1451   verifyFormat("var regex = /x(?=y)/;");
1452   verifyFormat("var regex = /x(?!y)/;");
1453   verifyFormat("var regex = /x|y/;");
1454   verifyFormat("var regex = /a{2}/;");
1455   verifyFormat("var regex = /a{1,3}/;");
1456 
1457   verifyFormat("var regex = /[abc]/;");
1458   verifyFormat("var regex = /[^abc]/;");
1459   verifyFormat("var regex = /[\\b]/;");
1460   verifyFormat("var regex = /[/]/;");
1461   verifyFormat("var regex = /[\\/]/;");
1462   verifyFormat("var regex = /\\[/;");
1463   verifyFormat("var regex = /\\\\[/]/;");
1464   verifyFormat("var regex = /}[\"]/;");
1465   verifyFormat("var regex = /}[/\"]/;");
1466   verifyFormat("var regex = /}[\"/]/;");
1467 
1468   verifyFormat("var regex = /\\b/;");
1469   verifyFormat("var regex = /\\B/;");
1470   verifyFormat("var regex = /\\d/;");
1471   verifyFormat("var regex = /\\D/;");
1472   verifyFormat("var regex = /\\f/;");
1473   verifyFormat("var regex = /\\n/;");
1474   verifyFormat("var regex = /\\r/;");
1475   verifyFormat("var regex = /\\s/;");
1476   verifyFormat("var regex = /\\S/;");
1477   verifyFormat("var regex = /\\t/;");
1478   verifyFormat("var regex = /\\v/;");
1479   verifyFormat("var regex = /\\w/;");
1480   verifyFormat("var regex = /\\W/;");
1481   verifyFormat("var regex = /a(a)\\1/;");
1482   verifyFormat("var regex = /\\0/;");
1483   verifyFormat("var regex = /\\\\/g;");
1484   verifyFormat("var regex = /\\a\\\\/g;");
1485   verifyFormat("var regex = /\a\\//g;");
1486   verifyFormat("var regex = /a\\//;\n"
1487                "var x = 0;");
1488   verifyFormat("var regex = /'/g;", "var regex = /'/g ;");
1489   verifyFormat("var regex = /'/g;  //'", "var regex = /'/g ; //'");
1490   verifyFormat("var regex = /\\/*/;\n"
1491                "var x = 0;",
1492                "var regex = /\\/*/;\n"
1493                "var x=0;");
1494   verifyFormat("var x = /a\\//;", "var x = /a\\//  \n;");
1495   verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
1496   verifyFormat("var regex =\n"
1497                "    /\"/;",
1498                getGoogleJSStyleWithColumns(15));
1499   verifyFormat("var regex =  //\n"
1500                "    /a/;");
1501   verifyFormat("var regexs = [\n"
1502                "  /d/,   //\n"
1503                "  /aa/,  //\n"
1504                "];");
1505 }
1506 
1507 TEST_F(FormatTestJS, RegexLiteralModifiers) {
1508   verifyFormat("var regex = /abc/g;");
1509   verifyFormat("var regex = /abc/i;");
1510   verifyFormat("var regex = /abc/m;");
1511   verifyFormat("var regex = /abc/y;");
1512 }
1513 
1514 TEST_F(FormatTestJS, RegexLiteralLength) {
1515   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1516                getGoogleJSStyleWithColumns(60));
1517   verifyFormat("var regex =\n"
1518                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1519                getGoogleJSStyleWithColumns(60));
1520   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1521                getGoogleJSStyleWithColumns(50));
1522 }
1523 
1524 TEST_F(FormatTestJS, RegexLiteralExamples) {
1525   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
1526 }
1527 
1528 TEST_F(FormatTestJS, IgnoresMpegTS) {
1529   std::string MpegTS(200, ' ');
1530   MpegTS.replace(0, strlen("nearlyLooks  +   like +   ts + code;  "),
1531                  "nearlyLooks  +   like +   ts + code;  ");
1532   MpegTS[0] = 0x47;
1533   MpegTS[188] = 0x47;
1534   verifyFormat(MpegTS, MpegTS);
1535 }
1536 
1537 TEST_F(FormatTestJS, TypeAnnotations) {
1538   verifyFormat("var x: string;");
1539   verifyFormat("var x: {a: string; b: number;} = {};");
1540   verifyFormat("function x(): string {\n  return 'x';\n}");
1541   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
1542   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
1543   verifyFormat("for (var y: string in x) {\n  x();\n}");
1544   verifyFormat("for (var y: string of x) {\n  x();\n}");
1545   verifyFormat("function x(y: {a?: number;} = {}): number {\n"
1546                "  return 12;\n"
1547                "}");
1548   verifyFormat("const x: Array<{a: number; b: string;}> = [];");
1549   verifyFormat("((a: string, b: number): string => a + b);");
1550   verifyFormat("var x: (y: number) => string;");
1551   verifyFormat("var x: P<string, (a: number) => string>;");
1552   verifyFormat("var x = {\n"
1553                "  y: function(): z {\n"
1554                "    return 1;\n"
1555                "  }\n"
1556                "};");
1557   verifyFormat("var x = {\n"
1558                "  y: function(): {a: number} {\n"
1559                "    return 1;\n"
1560                "  }\n"
1561                "};");
1562   verifyFormat("function someFunc(args: string[]):\n"
1563                "    {longReturnValue: string[]} {}",
1564                getGoogleJSStyleWithColumns(60));
1565   verifyFormat(
1566       "var someValue = (v as aaaaaaaaaaaaaaaaaaaa<T>[])\n"
1567       "                    .someFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1568   verifyFormat("const xIsALongIdent:\n"
1569                "    YJustBarelyFitsLinex[];",
1570                getGoogleJSStyleWithColumns(20));
1571   verifyFormat("const x = {\n"
1572                "  y: 1\n"
1573                "} as const;");
1574 }
1575 
1576 TEST_F(FormatTestJS, UnionIntersectionTypes) {
1577   verifyFormat("let x: A|B = A | B;");
1578   verifyFormat("let x: A&B|C = A & B;");
1579   verifyFormat("let x: Foo<A|B> = new Foo<A|B>();");
1580   verifyFormat("function(x: A|B): C&D {}");
1581   verifyFormat("function(x: A|B = A | B): C&D {}");
1582   verifyFormat("function x(path: number|string) {}");
1583   verifyFormat("function x(): string|number {}");
1584   verifyFormat("type Foo = Bar|Baz;");
1585   verifyFormat("type Foo = Bar<X>|Baz;");
1586   verifyFormat("type Foo = (Bar<X>|Baz);");
1587   verifyFormat("let x: Bar|Baz;");
1588   verifyFormat("let x: Bar<X>|Baz;");
1589   verifyFormat("let x: (Foo|Bar)[];");
1590   verifyFormat("type X = {\n"
1591                "  a: Foo|Bar;\n"
1592                "};");
1593   verifyFormat("export type X = {\n"
1594                "  a: Foo|Bar;\n"
1595                "};");
1596 }
1597 
1598 TEST_F(FormatTestJS, UnionIntersectionTypesInObjectType) {
1599   verifyFormat("let x: {x: number|null} = {x: number | null};");
1600   verifyFormat("let nested: {x: {y: number|null}};");
1601   verifyFormat("let mixed: {x: [number|null, {w: number}]};");
1602   verifyFormat("class X {\n"
1603                "  contructor(x: {\n"
1604                "    a: a|null,\n"
1605                "    b: b|null,\n"
1606                "  }) {}\n"
1607                "}");
1608 }
1609 
1610 TEST_F(FormatTestJS, ClassDeclarations) {
1611   verifyFormat("class C {\n  x: string = 12;\n}");
1612   verifyFormat("class C {\n  x(): string => 12;\n}");
1613   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
1614   verifyFormat("class C {\n"
1615                "  foo() {}\n"
1616                "  [bar]() {}\n"
1617                "}\n");
1618   verifyFormat("class C {\n  private x: string = 12;\n}");
1619   verifyFormat("class C {\n  private static x: string = 12;\n}");
1620   verifyFormat("class C {\n  static x(): string {\n    return 'asd';\n  }\n}");
1621   verifyFormat("class C extends P implements I {}");
1622   verifyFormat("class C extends p.P implements i.I {}");
1623   verifyFormat("x(class {\n"
1624                "  a(): A {}\n"
1625                "});");
1626   verifyFormat("class Test {\n"
1627                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
1628                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
1629                "}");
1630   verifyFormat("foo = class Name {\n"
1631                "  constructor() {}\n"
1632                "};");
1633   verifyFormat("foo = class {\n"
1634                "  constructor() {}\n"
1635                "};");
1636   verifyFormat("class C {\n"
1637                "  x: {y: Z;} = {};\n"
1638                "  private y: {y: Z;} = {};\n"
1639                "}");
1640 
1641   // ':' is not a type declaration here.
1642   verifyFormat("class X {\n"
1643                "  subs = {\n"
1644                "    'b': {\n"
1645                "      'c': 1,\n"
1646                "    },\n"
1647                "  };\n"
1648                "}");
1649   verifyFormat("@Component({\n"
1650                "  moduleId: module.id,\n"
1651                "})\n"
1652                "class SessionListComponent implements OnDestroy, OnInit {\n"
1653                "}");
1654 }
1655 
1656 TEST_F(FormatTestJS, StrictPropInitWrap) {
1657   const FormatStyle &Style = getGoogleJSStyleWithColumns(22);
1658   verifyFormat("class X {\n"
1659                "  strictPropInitField!:\n"
1660                "      string;\n"
1661                "}",
1662                Style);
1663 }
1664 
1665 TEST_F(FormatTestJS, InterfaceDeclarations) {
1666   verifyFormat("interface I {\n"
1667                "  x: string;\n"
1668                "  enum: string[];\n"
1669                "  enum?: string[];\n"
1670                "}\n"
1671                "var y;");
1672   // Ensure that state is reset after parsing the interface.
1673   verifyFormat("interface a {}\n"
1674                "export function b() {}\n"
1675                "var x;");
1676 
1677   // Arrays of object type literals.
1678   verifyFormat("interface I {\n"
1679                "  o: {}[];\n"
1680                "}");
1681 }
1682 
1683 TEST_F(FormatTestJS, ObjectTypesInExtendsImplements) {
1684   verifyFormat("class C extends {} {}");
1685   verifyFormat("class C implements {bar: number} {}");
1686   // Somewhat odd, but probably closest to reasonable formatting?
1687   verifyFormat("class C implements {\n"
1688                "  bar: number,\n"
1689                "  baz: string,\n"
1690                "} {}");
1691   verifyFormat("class C<P extends {}> {}");
1692 }
1693 
1694 TEST_F(FormatTestJS, EnumDeclarations) {
1695   verifyFormat("enum Foo {\n"
1696                "  A = 1,\n"
1697                "  B\n"
1698                "}");
1699   verifyFormat("export /* somecomment*/ enum Foo {\n"
1700                "  A = 1,\n"
1701                "  B\n"
1702                "}");
1703   verifyFormat("enum Foo {\n"
1704                "  A = 1,  // comment\n"
1705                "  B\n"
1706                "}\n"
1707                "var x = 1;");
1708   verifyFormat("const enum Foo {\n"
1709                "  A = 1,\n"
1710                "  B\n"
1711                "}");
1712   verifyFormat("export const enum Foo {\n"
1713                "  A = 1,\n"
1714                "  B\n"
1715                "}");
1716 }
1717 
1718 TEST_F(FormatTestJS, Decorators) {
1719   verifyFormat("@A\nclass C {\n}");
1720   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
1721   verifyFormat("@A\n@B\nclass C {\n}");
1722   verifyFormat("class C {\n  @A x: string;\n}");
1723   verifyFormat("class C {\n"
1724                "  @A\n"
1725                "  private x(): string {\n"
1726                "    return 'y';\n"
1727                "  }\n"
1728                "}");
1729   verifyFormat("class C {\n"
1730                "  private x(@A x: string) {}\n"
1731                "}");
1732   verifyFormat("class X {}\n"
1733                "class Y {}");
1734   verifyFormat("class X {\n"
1735                "  @property() private isReply = false;\n"
1736                "}\n");
1737 }
1738 
1739 TEST_F(FormatTestJS, TypeAliases) {
1740   verifyFormat("type X = number;\n"
1741                "class C {}");
1742   verifyFormat("type X<Y> = Z<Y>;");
1743   verifyFormat("type X = {\n"
1744                "  y: number\n"
1745                "};\n"
1746                "class C {}");
1747   verifyFormat("export type X = {\n"
1748                "  a: string,\n"
1749                "  b?: string,\n"
1750                "};\n");
1751 }
1752 
1753 TEST_F(FormatTestJS, TypeInterfaceLineWrapping) {
1754   const FormatStyle &Style = getGoogleJSStyleWithColumns(20);
1755   verifyFormat("type LongTypeIsReallyUnreasonablyLong =\n"
1756                "    string;\n",
1757                "type LongTypeIsReallyUnreasonablyLong = string;\n", Style);
1758   verifyFormat("interface AbstractStrategyFactoryProvider {\n"
1759                "  a: number\n"
1760                "}\n",
1761                "interface AbstractStrategyFactoryProvider { a: number }\n",
1762                Style);
1763 }
1764 
1765 TEST_F(FormatTestJS, RemoveEmptyLinesInArrowFunctions) {
1766   verifyFormat("x = () => {\n"
1767                "  foo();\n"
1768                "  bar();\n"
1769                "};\n",
1770                "x = () => {\n"
1771                "\n"
1772                "  foo();\n"
1773                "  bar();\n"
1774                "\n"
1775                "};\n");
1776 }
1777 
1778 TEST_F(FormatTestJS, Modules) {
1779   verifyFormat("import SomeThing from 'some/module.js';");
1780   verifyFormat("import {X, Y} from 'some/module.js';");
1781   verifyFormat("import a, {X, Y} from 'some/module.js';");
1782   verifyFormat("import {X, Y,} from 'some/module.js';");
1783   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
1784   // Ensure Automatic Semicolon Insertion does not break on "as\n".
1785   verifyFormat("import {X as myX} from 'm';", "import {X as\n"
1786                                               " myX} from 'm';");
1787   verifyFormat("import * as lib from 'some/module.js';");
1788   verifyFormat("var x = {import: 1};\nx.import = 2;");
1789 
1790   verifyFormat("export function fn() {\n"
1791                "  return 'fn';\n"
1792                "}");
1793   verifyFormat("export function A() {}\n"
1794                "export default function B() {}\n"
1795                "export function C() {}");
1796   verifyFormat("export default () => {\n"
1797                "  let x = 1;\n"
1798                "  return x;\n"
1799                "}");
1800   verifyFormat("export const x = 12;");
1801   verifyFormat("export default class X {}");
1802   verifyFormat("export {X, Y} from 'some/module.js';");
1803   verifyFormat("export {X, Y,} from 'some/module.js';");
1804   verifyFormat("export {SomeVeryLongExport as X, "
1805                "SomeOtherVeryLongExport as Y} from 'some/module.js';");
1806   // export without 'from' is wrapped.
1807   verifyFormat("export let someRatherLongVariableName =\n"
1808                "    someSurprisinglyLongVariable + someOtherRatherLongVar;");
1809   // ... but not if from is just an identifier.
1810   verifyFormat("export {\n"
1811                "  from as from,\n"
1812                "  someSurprisinglyLongVariable as\n"
1813                "      from\n"
1814                "};",
1815                getGoogleJSStyleWithColumns(20));
1816   verifyFormat("export class C {\n"
1817                "  x: number;\n"
1818                "  y: string;\n"
1819                "}");
1820   verifyFormat("export class X {\n"
1821                "  y: number;\n"
1822                "}");
1823   verifyFormat("export abstract class X {\n"
1824                "  y: number;\n"
1825                "}");
1826   verifyFormat("export default class X {\n"
1827                "  y: number\n"
1828                "}");
1829   verifyFormat("export default function() {\n  return 1;\n}");
1830   verifyFormat("export var x = 12;");
1831   verifyFormat("class C {}\n"
1832                "export function f() {}\n"
1833                "var v;");
1834   verifyFormat("export var x: number = 12;");
1835   verifyFormat("export const y = {\n"
1836                "  a: 1,\n"
1837                "  b: 2\n"
1838                "};");
1839   verifyFormat("export enum Foo {\n"
1840                "  BAR,\n"
1841                "  // adsdasd\n"
1842                "  BAZ\n"
1843                "}");
1844   verifyFormat("export default [\n"
1845                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1846                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
1847                "];");
1848   verifyFormat("export default [];");
1849   verifyFormat("export default () => {};");
1850   verifyFormat("export default () => {\n"
1851                "  x;\n"
1852                "  x;\n"
1853                "};");
1854   verifyFormat("export interface Foo {\n"
1855                "  foo: number;\n"
1856                "}\n"
1857                "export class Bar {\n"
1858                "  blah(): string {\n"
1859                "    return this.blah;\n"
1860                "  };\n"
1861                "}");
1862 }
1863 
1864 TEST_F(FormatTestJS, ImportWrapping) {
1865   verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
1866                " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
1867                "} from 'some/module.js';");
1868   FormatStyle Style = getGoogleJSStyleWithColumns(80);
1869   Style.JavaScriptWrapImports = true;
1870   verifyFormat("import {\n"
1871                "  VeryLongImportsAreAnnoying,\n"
1872                "  VeryLongImportsAreAnnoying,\n"
1873                "  VeryLongImportsAreAnnoying,\n"
1874                "} from 'some/module.js';",
1875                Style);
1876   verifyFormat("import {\n"
1877                "  A,\n"
1878                "  A,\n"
1879                "} from 'some/module.js';",
1880                Style);
1881   verifyFormat("export {\n"
1882                "  A,\n"
1883                "  A,\n"
1884                "} from 'some/module.js';",
1885                Style);
1886   Style.ColumnLimit = 40;
1887   // Using this version of verifyFormat because test::messUp hides the issue.
1888   verifyFormat("import {\n"
1889                "  A,\n"
1890                "} from\n"
1891                "    'some/path/longer/than/column/limit/module.js';",
1892                " import  {  \n"
1893                "    A,  \n"
1894                "  }    from\n"
1895                "      'some/path/longer/than/column/limit/module.js'  ; ",
1896                Style);
1897 }
1898 
1899 TEST_F(FormatTestJS, TemplateStrings) {
1900   // Keeps any whitespace/indentation within the template string.
1901   verifyFormat("var x = `hello\n"
1902                "     ${name}\n"
1903                "  !`;",
1904                "var x    =    `hello\n"
1905                "     ${  name    }\n"
1906                "  !`;");
1907 
1908   verifyFormat("var x =\n"
1909                "    `hello ${world}` >= some();",
1910                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
1911   verifyFormat("var x = `hello ${world}` >= some();",
1912                getGoogleJSStyleWithColumns(35)); // Barely fits.
1913   verifyFormat("var x = `hellö ${wörld}` >= söme();",
1914                getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8.
1915   verifyFormat("var x = `hello\n"
1916                "  ${world}` >=\n"
1917                "    some();",
1918                "var x =\n"
1919                "    `hello\n"
1920                "  ${world}` >= some();",
1921                getGoogleJSStyleWithColumns(21)); // Barely doesn't fit.
1922   verifyFormat("var x = `hello\n"
1923                "  ${world}` >= some();",
1924                "var x =\n"
1925                "    `hello\n"
1926                "  ${world}` >= some();",
1927                getGoogleJSStyleWithColumns(22)); // Barely fits.
1928 
1929   verifyFormat("var x =\n"
1930                "    `h`;",
1931                getGoogleJSStyleWithColumns(11));
1932   verifyFormat("var x =\n    `multi\n  line`;", "var x = `multi\n  line`;",
1933                getGoogleJSStyleWithColumns(13));
1934   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1935                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
1936   // Repro for an obscure width-miscounting issue with template strings.
1937   verifyFormat(
1938       "someLongVariable =\n"
1939       "    "
1940       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;",
1941       "someLongVariable = "
1942       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;");
1943 
1944   // Make sure template strings get a proper ColumnWidth assigned, even if they
1945   // are first token in line.
1946   verifyFormat("var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1947                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
1948 
1949   // Two template strings.
1950   verifyFormat("var x = `hello` == `hello`;");
1951 
1952   // Comments in template strings.
1953   verifyFormat("var x = `//a`;\n"
1954                "var y;",
1955                "var x =\n `//a`;\n"
1956                "var y  ;");
1957   verifyFormat("var x = `/*a`;\n"
1958                "var y;",
1959                "var x =\n `/*a`;\n"
1960                "var y;");
1961   // Unterminated string literals in a template string.
1962   verifyFormat("var x = `'`;  // comment with matching quote '\n"
1963                "var y;");
1964   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
1965                "var y;");
1966   verifyFormat("it(`'aaaaaaaaaaaaaaa   `, aaaaaaaaa);",
1967                "it(`'aaaaaaaaaaaaaaa   `,   aaaaaaaaa) ;",
1968                getGoogleJSStyleWithColumns(40));
1969   // Backticks in a comment - not a template string.
1970   verifyFormat("var x = 1  // `/*a`;\n"
1971                "    ;",
1972                "var x =\n 1  // `/*a`;\n"
1973                "    ;");
1974   verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */");
1975   // Comment spans multiple template strings.
1976   verifyFormat("var x = `/*a`;\n"
1977                "var y = ` */ `;",
1978                "var x =\n `/*a`;\n"
1979                "var y =\n ` */ `;");
1980   // Escaped backtick.
1981   verifyFormat("var x = ` \\` a`;\n"
1982                "var y;",
1983                "var x = ` \\` a`;\n"
1984                "var y;");
1985   // Escaped dollar.
1986   verifyFormat("var x = ` \\${foo}`;\n");
1987 
1988   // The token stream can contain two string_literals in sequence, but that
1989   // doesn't mean that they are implicitly concatenated in JavaScript.
1990   verifyFormat("var f = `aaaa ${a ? 'a' : 'b'}`;");
1991 
1992   // Ensure that scopes are appropriately set around evaluated expressions in
1993   // template strings.
1994   verifyFormat("var f = `aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa\n"
1995                "         aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`;",
1996                "var f = `aaaaaaaaaaaaa:${aaaaaaa.  aaaaa} aaaaaaaa\n"
1997                "         aaaaaaaaaaaaa:${  aaaaaaa. aaaaa} aaaaaaaa`;");
1998   verifyFormat("var x = someFunction(`${})`)  //\n"
1999                "            .oooooooooooooooooon();");
2000   verifyFormat("var x = someFunction(`${aaaa}${\n"
2001                "    aaaaa(  //\n"
2002                "        aaaaa)})`);");
2003 }
2004 
2005 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) {
2006   verifyFormat("var f = `aaaaaaaaaaaaaaaaaa: ${\n"
2007                "    aaaaa +  //\n"
2008                "    bbbb}`;",
2009                "var f = `aaaaaaaaaaaaaaaaaa: ${aaaaa +  //\n"
2010                "                               bbbb}`;");
2011   verifyFormat("var f = `\n"
2012                "  aaaaaaaaaaaaaaaaaa: ${\n"
2013                "    aaaaa +  //\n"
2014                "    bbbb}`;",
2015                "var f  =  `\n"
2016                "  aaaaaaaaaaaaaaaaaa: ${   aaaaa  +  //\n"
2017                "                        bbbb }`;");
2018   verifyFormat("var f = `\n"
2019                "  aaaaaaaaaaaaaaaaaa: ${\n"
2020                "    someFunction(\n"
2021                "        aaaaa +  //\n"
2022                "        bbbb)}`;",
2023                "var f  =  `\n"
2024                "  aaaaaaaaaaaaaaaaaa: ${someFunction (\n"
2025                "                            aaaaa  +   //\n"
2026                "                            bbbb)}`;");
2027 
2028   // It might be preferable to wrap before "someFunction".
2029   verifyFormat("var f = `\n"
2030                "  aaaaaaaaaaaaaaaaaa: ${someFunction({\n"
2031                "  aaaa: aaaaa,\n"
2032                "  bbbb: bbbbb,\n"
2033                "})}`;",
2034                "var f  =  `\n"
2035                "  aaaaaaaaaaaaaaaaaa: ${someFunction ({\n"
2036                "                          aaaa:  aaaaa,\n"
2037                "                          bbbb:  bbbbb,\n"
2038                "                        })}`;");
2039 }
2040 
2041 TEST_F(FormatTestJS, TemplateStringASI) {
2042   verifyFormat("var x = `hello${world}`;", "var x = `hello${\n"
2043                                            "    world\n"
2044                                            "}`;");
2045 }
2046 
2047 TEST_F(FormatTestJS, NestedTemplateStrings) {
2048   verifyFormat(
2049       "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;");
2050   verifyFormat("var x = `he${({text: 'll'}.text)}o`;");
2051 
2052   // Crashed at some point.
2053   verifyFormat("}");
2054 }
2055 
2056 TEST_F(FormatTestJS, TaggedTemplateStrings) {
2057   verifyFormat("var x = html`<ul>`;");
2058   verifyFormat("yield `hello`;");
2059   verifyFormat("var f = {\n"
2060                "  param: longTagName`This is a ${\n"
2061                "                    'really'} long line`\n"
2062                "};",
2063                "var f = {param: longTagName`This is a ${'really'} long line`};",
2064                getGoogleJSStyleWithColumns(40));
2065 }
2066 
2067 TEST_F(FormatTestJS, CastSyntax) {
2068   verifyFormat("var x = <type>foo;");
2069   verifyFormat("var x = foo as type;");
2070   verifyFormat("let x = (a + b) as\n"
2071                "    LongTypeIsLong;",
2072                getGoogleJSStyleWithColumns(20));
2073   verifyFormat("foo = <Bar[]>[\n"
2074                "  1,  //\n"
2075                "  2\n"
2076                "];");
2077   verifyFormat("var x = [{x: 1} as type];");
2078   verifyFormat("x = x as [a, b];");
2079   verifyFormat("x = x as {a: string};");
2080   verifyFormat("x = x as (string);");
2081   verifyFormat("x = x! as (string);");
2082   verifyFormat("x = y! in z;");
2083   verifyFormat("var x = something.someFunction() as\n"
2084                "    something;",
2085                getGoogleJSStyleWithColumns(40));
2086 }
2087 
2088 TEST_F(FormatTestJS, TypeArguments) {
2089   verifyFormat("class X<Y> {}");
2090   verifyFormat("new X<Y>();");
2091   verifyFormat("foo<Y>(a);");
2092   verifyFormat("var x: X<Y>[];");
2093   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
2094   verifyFormat("function f(a: List<any> = null) {}");
2095   verifyFormat("function f(): List<any> {}");
2096   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
2097                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
2098   verifyFormat("function aaaaaaaaaa(\n"
2099                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
2100                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
2101                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
2102 }
2103 
2104 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
2105   verifyFormat(
2106       "function foo(check: Object):\n"
2107       "    check is {foo: string, bar: string, baz: string, foobar: string} {\n"
2108       "  return 'bar' in check;\n"
2109       "}\n");
2110 }
2111 
2112 TEST_F(FormatTestJS, OptionalTypes) {
2113   verifyFormat("function x(a?: b, c?, d?) {}");
2114   verifyFormat("class X {\n"
2115                "  y?: z;\n"
2116                "  z?;\n"
2117                "}");
2118   verifyFormat("interface X {\n"
2119                "  y?(): z;\n"
2120                "}");
2121   verifyFormat("constructor({aa}: {\n"
2122                "  aa?: string,\n"
2123                "  aaaaaaaa?: string,\n"
2124                "  aaaaaaaaaaaaaaa?: boolean,\n"
2125                "  aaaaaa?: List<string>\n"
2126                "}) {}");
2127 }
2128 
2129 TEST_F(FormatTestJS, IndexSignature) {
2130   verifyFormat("var x: {[k: string]: v};");
2131 }
2132 
2133 TEST_F(FormatTestJS, WrapAfterParen) {
2134   verifyFormat("xxxxxxxxxxx(\n"
2135                "    aaa, aaa);",
2136                getGoogleJSStyleWithColumns(20));
2137   verifyFormat("xxxxxxxxxxx(\n"
2138                "    aaa, aaa, aaa,\n"
2139                "    aaa, aaa, aaa);",
2140                getGoogleJSStyleWithColumns(20));
2141   verifyFormat("xxxxxxxxxxx(\n"
2142                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
2143                "    function(x) {\n"
2144                "      y();  //\n"
2145                "    });",
2146                getGoogleJSStyleWithColumns(40));
2147   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
2148                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2149 }
2150 
2151 TEST_F(FormatTestJS, JSDocAnnotations) {
2152   verifyFormat("/**\n"
2153                " * @exports {this.is.a.long.path.to.a.Type}\n"
2154                " */",
2155                "/**\n"
2156                " * @exports {this.is.a.long.path.to.a.Type}\n"
2157                " */",
2158                getGoogleJSStyleWithColumns(20));
2159   verifyFormat("/**\n"
2160                " * @mods {this.is.a.long.path.to.a.Type}\n"
2161                " */",
2162                "/**\n"
2163                " * @mods {this.is.a.long.path.to.a.Type}\n"
2164                " */",
2165                getGoogleJSStyleWithColumns(20));
2166   verifyFormat("/**\n"
2167                " * @mods {this.is.a.long.path.to.a.Type}\n"
2168                " */",
2169                "/**\n"
2170                " * @mods {this.is.a.long.path.to.a.Type}\n"
2171                " */",
2172                getGoogleJSStyleWithColumns(20));
2173   verifyFormat("/**\n"
2174                " * @param {canWrap\n"
2175                " *     onSpace}\n"
2176                " */",
2177                "/**\n"
2178                " * @param {canWrap onSpace}\n"
2179                " */",
2180                getGoogleJSStyleWithColumns(20));
2181   // make sure clang-format doesn't break before *any* '{'
2182   verifyFormat("/**\n"
2183                " * @lala {lala {lalala\n"
2184                " */\n",
2185                "/**\n"
2186                " * @lala {lala {lalala\n"
2187                " */\n",
2188                getGoogleJSStyleWithColumns(20));
2189   // cases where '{' is around the column limit
2190   for (int ColumnLimit = 6; ColumnLimit < 13; ++ColumnLimit) {
2191     verifyFormat("/**\n"
2192                  " * @param {type}\n"
2193                  " */",
2194                  "/**\n"
2195                  " * @param {type}\n"
2196                  " */",
2197                  getGoogleJSStyleWithColumns(ColumnLimit));
2198   }
2199   // don't break before @tags
2200   verifyFormat("/**\n"
2201                " * This\n"
2202                " * tag @param\n"
2203                " * stays.\n"
2204                " */",
2205                "/**\n"
2206                " * This tag @param stays.\n"
2207                " */",
2208                getGoogleJSStyleWithColumns(13));
2209   verifyFormat("/**\n"
2210                " * @see http://very/very/long/url/is/long\n"
2211                " */",
2212                "/**\n"
2213                " * @see http://very/very/long/url/is/long\n"
2214                " */",
2215                getGoogleJSStyleWithColumns(20));
2216   verifyFormat("/**\n"
2217                " * @param This is a\n"
2218                " *     long comment\n"
2219                " *     but no type\n"
2220                " */",
2221                "/**\n"
2222                " * @param This is a long comment but no type\n"
2223                " */",
2224                getGoogleJSStyleWithColumns(20));
2225   // Break and reindent @param line and reflow unrelated lines.
2226   EXPECT_EQ("{\n"
2227             "  /**\n"
2228             "   * long long long\n"
2229             "   * long\n"
2230             "   * @param {this.is.a.long.path.to.a.Type}\n"
2231             "   *     a\n"
2232             "   * long long long\n"
2233             "   * long long\n"
2234             "   */\n"
2235             "  function f(a) {}\n"
2236             "}",
2237             format("{\n"
2238                    "/**\n"
2239                    " * long long long long\n"
2240                    " * @param {this.is.a.long.path.to.a.Type} a\n"
2241                    " * long long long long\n"
2242                    " * long\n"
2243                    " */\n"
2244                    "  function f(a) {}\n"
2245                    "}",
2246                    getGoogleJSStyleWithColumns(20)));
2247 }
2248 
2249 TEST_F(FormatTestJS, TslintComments) {
2250   // tslint uses pragma comments that must be on their own line.
2251   verifyFormat("// Comment that needs wrapping. Comment that needs wrapping. "
2252                "Comment that needs\n"
2253                "// wrapping. Trailing line.\n"
2254                "// tslint:disable-next-line:must-be-on-own-line",
2255                "// Comment that needs wrapping. Comment that needs wrapping. "
2256                "Comment that needs wrapping.\n"
2257                "// Trailing line.\n"
2258                "// tslint:disable-next-line:must-be-on-own-line");
2259 }
2260 
2261 TEST_F(FormatTestJS, TscComments) {
2262   // As above, @ts-ignore and @ts-check comments must be on their own line.
2263   verifyFormat("// Comment that needs wrapping. Comment that needs wrapping. "
2264                "Comment that needs\n"
2265                "// wrapping. Trailing line.\n"
2266                "// @ts-ignore",
2267                "// Comment that needs wrapping. Comment that needs wrapping. "
2268                "Comment that needs wrapping.\n"
2269                "// Trailing line.\n"
2270                "// @ts-ignore");
2271   verifyFormat("// Comment that needs wrapping. Comment that needs wrapping. "
2272                "Comment that needs\n"
2273                "// wrapping. Trailing line.\n"
2274                "// @ts-check",
2275                "// Comment that needs wrapping. Comment that needs wrapping. "
2276                "Comment that needs wrapping.\n"
2277                "// Trailing line.\n"
2278                "// @ts-check");
2279 }
2280 
2281 TEST_F(FormatTestJS, RequoteStringsSingle) {
2282   verifyFormat("var x = 'foo';", "var x = \"foo\";");
2283   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";");
2284   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";");
2285   verifyFormat("var x =\n"
2286                "    'foo\\'';",
2287                // Code below is 15 chars wide, doesn't fit into the line with
2288                // the \ escape added.
2289                "var x = \"foo'\";", getGoogleJSStyleWithColumns(15));
2290   // Removes no-longer needed \ escape from ".
2291   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";");
2292   // Code below fits into 15 chars *after* removing the \ escape.
2293   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";",
2294                getGoogleJSStyleWithColumns(15));
2295   verifyFormat("// clang-format off\n"
2296                "let x = \"double\";\n"
2297                "// clang-format on\n"
2298                "let x = 'single';\n",
2299                "// clang-format off\n"
2300                "let x = \"double\";\n"
2301                "// clang-format on\n"
2302                "let x = \"single\";\n");
2303 }
2304 
2305 TEST_F(FormatTestJS, RequoteAndIndent) {
2306   verifyFormat("let x = someVeryLongFunctionThatGoesOnAndOn(\n"
2307                "    'double quoted string that needs wrapping');",
2308                "let x = someVeryLongFunctionThatGoesOnAndOn("
2309                "\"double quoted string that needs wrapping\");");
2310 
2311   verifyFormat("let x =\n"
2312                "    'foo\\'oo';\n"
2313                "let x =\n"
2314                "    'foo\\'oo';",
2315                "let x=\"foo'oo\";\n"
2316                "let x=\"foo'oo\";",
2317                getGoogleJSStyleWithColumns(15));
2318 }
2319 
2320 TEST_F(FormatTestJS, RequoteStringsDouble) {
2321   FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2322   DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double;
2323   verifyFormat("var x = \"foo\";", DoubleQuotes);
2324   verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes);
2325   verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes);
2326 }
2327 
2328 TEST_F(FormatTestJS, RequoteStringsLeave) {
2329   FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2330   LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave;
2331   verifyFormat("var x = \"foo\";", LeaveQuotes);
2332   verifyFormat("var x = 'foo';", LeaveQuotes);
2333 }
2334 
2335 TEST_F(FormatTestJS, SupportShebangLines) {
2336   verifyFormat("#!/usr/bin/env node\n"
2337                "var x = hello();",
2338                "#!/usr/bin/env node\n"
2339                "var x   =  hello();");
2340 }
2341 
2342 TEST_F(FormatTestJS, NonNullAssertionOperator) {
2343   verifyFormat("let x = foo!.bar();\n");
2344   verifyFormat("let x = foo ? bar! : baz;\n");
2345   verifyFormat("let x = !foo;\n");
2346   verifyFormat("if (!+a) {\n}");
2347   verifyFormat("let x = foo[0]!;\n");
2348   verifyFormat("let x = (foo)!;\n");
2349   verifyFormat("let x = x(foo!);\n");
2350   verifyFormat("a.aaaaaa(a.a!).then(\n"
2351                "    x => x(x));\n",
2352                getGoogleJSStyleWithColumns(20));
2353   verifyFormat("let x = foo! - 1;\n");
2354   verifyFormat("let x = {foo: 1}!;\n");
2355   verifyFormat("let x = hello.foo()!\n"
2356                "            .foo()!\n"
2357                "            .foo()!\n"
2358                "            .foo()!;\n",
2359                getGoogleJSStyleWithColumns(20));
2360   verifyFormat("let x = namespace!;\n");
2361   verifyFormat("return !!x;\n");
2362 }
2363 
2364 TEST_F(FormatTestJS, CppKeywords) {
2365   // Make sure we don't mess stuff up because of C++ keywords.
2366   verifyFormat("return operator && (aa);");
2367   // .. or QT ones.
2368   verifyFormat("const slots: Slot[];");
2369   // use the "!" assertion operator to validate that clang-format understands
2370   // these C++ keywords aren't keywords in JS/TS.
2371   verifyFormat("auto!;");
2372   verifyFormat("char!;");
2373   verifyFormat("concept!;");
2374   verifyFormat("double!;");
2375   verifyFormat("extern!;");
2376   verifyFormat("float!;");
2377   verifyFormat("inline!;");
2378   verifyFormat("int!;");
2379   verifyFormat("long!;");
2380   verifyFormat("register!;");
2381   verifyFormat("restrict!;");
2382   verifyFormat("sizeof!;");
2383   verifyFormat("struct!;");
2384   verifyFormat("typedef!;");
2385   verifyFormat("union!;");
2386   verifyFormat("unsigned!;");
2387   verifyFormat("volatile!;");
2388   verifyFormat("_Alignas!;");
2389   verifyFormat("_Alignof!;");
2390   verifyFormat("_Atomic!;");
2391   verifyFormat("_Bool!;");
2392   verifyFormat("_Complex!;");
2393   verifyFormat("_Generic!;");
2394   verifyFormat("_Imaginary!;");
2395   verifyFormat("_Noreturn!;");
2396   verifyFormat("_Static_assert!;");
2397   verifyFormat("_Thread_local!;");
2398   verifyFormat("__func__!;");
2399   verifyFormat("__objc_yes!;");
2400   verifyFormat("__objc_no!;");
2401   verifyFormat("asm!;");
2402   verifyFormat("bool!;");
2403   verifyFormat("const_cast!;");
2404   verifyFormat("dynamic_cast!;");
2405   verifyFormat("explicit!;");
2406   verifyFormat("friend!;");
2407   verifyFormat("mutable!;");
2408   verifyFormat("operator!;");
2409   verifyFormat("reinterpret_cast!;");
2410   verifyFormat("static_cast!;");
2411   verifyFormat("template!;");
2412   verifyFormat("typename!;");
2413   verifyFormat("typeid!;");
2414   verifyFormat("using!;");
2415   verifyFormat("virtual!;");
2416   verifyFormat("wchar_t!;");
2417 
2418   // Positive tests:
2419   verifyFormat("x.type!;");
2420   verifyFormat("x.get!;");
2421   verifyFormat("x.set!;");
2422 }
2423 
2424 TEST_F(FormatTestJS, NullPropagatingOperator) {
2425   verifyFormat("let x = foo?.bar?.baz();\n");
2426   verifyFormat("let x = foo?.(foo);\n");
2427   verifyFormat("let x = foo?.['arr'];\n");
2428 }
2429 
2430 TEST_F(FormatTestJS, NullishCoalescingOperator) {
2431   verifyFormat("const val = something ?? 'some other default';\n");
2432   verifyFormat(
2433       "const val = something ?? otherDefault ??\n"
2434       "    evenMore ?? evenMore;\n",
2435       "const val = something ?? otherDefault ?? evenMore ?? evenMore;\n",
2436       getGoogleJSStyleWithColumns(40));
2437 }
2438 
2439 TEST_F(FormatTestJS, AssignmentOperators) {
2440   verifyFormat("a &&= b;\n");
2441   verifyFormat("a ||= b;\n");
2442   // NB: need to split ? ?= to avoid it being interpreted by C++ as a trigraph
2443   // for #.
2444   verifyFormat("a ?"
2445                "?= b;\n");
2446 }
2447 
2448 TEST_F(FormatTestJS, Conditional) {
2449   verifyFormat("y = x ? 1 : 2;");
2450   verifyFormat("x ? 1 : 2;");
2451   verifyFormat("class Foo {\n"
2452                "  field = true ? 1 : 2;\n"
2453                "  method(a = true ? 1 : 2) {}\n"
2454                "}");
2455 }
2456 
2457 TEST_F(FormatTestJS, ImportComments) {
2458   verifyFormat("import {x} from 'x';  // from some location",
2459                getGoogleJSStyleWithColumns(25));
2460   verifyFormat("// taze: x from 'location'", getGoogleJSStyleWithColumns(10));
2461   verifyFormat("/// <reference path=\"some/location\" />",
2462                getGoogleJSStyleWithColumns(10));
2463 }
2464 
2465 TEST_F(FormatTestJS, Exponentiation) {
2466   verifyFormat("squared = x ** 2;");
2467   verifyFormat("squared **= 2;");
2468 }
2469 
2470 TEST_F(FormatTestJS, NestedLiterals) {
2471   FormatStyle FourSpaces = getGoogleJSStyleWithColumns(15);
2472   FourSpaces.IndentWidth = 4;
2473   verifyFormat("var l = [\n"
2474                "    [\n"
2475                "        1,\n"
2476                "    ],\n"
2477                "];",
2478                FourSpaces);
2479   verifyFormat("var l = [\n"
2480                "    {\n"
2481                "        1: 1,\n"
2482                "    },\n"
2483                "];",
2484                FourSpaces);
2485   verifyFormat("someFunction(\n"
2486                "    p1,\n"
2487                "    [\n"
2488                "        1,\n"
2489                "    ],\n"
2490                ");",
2491                FourSpaces);
2492   verifyFormat("someFunction(\n"
2493                "    p1,\n"
2494                "    {\n"
2495                "        1: 1,\n"
2496                "    },\n"
2497                ");",
2498                FourSpaces);
2499   verifyFormat("var o = {\n"
2500                "    1: 1,\n"
2501                "    2: {\n"
2502                "        3: 3,\n"
2503                "    },\n"
2504                "};",
2505                FourSpaces);
2506   verifyFormat("var o = {\n"
2507                "    1: 1,\n"
2508                "    2: [\n"
2509                "        3,\n"
2510                "    ],\n"
2511                "};",
2512                FourSpaces);
2513 }
2514 
2515 TEST_F(FormatTestJS, BackslashesInComments) {
2516   verifyFormat("// hello \\\n"
2517                "if (x) foo();\n",
2518                "// hello \\\n"
2519                "     if ( x) \n"
2520                "   foo();\n");
2521   verifyFormat("/* ignore \\\n"
2522                " */\n"
2523                "if (x) foo();\n",
2524                "/* ignore \\\n"
2525                " */\n"
2526                " if (  x) foo();\n");
2527   verifyFormat("// st \\ art\\\n"
2528                "// comment"
2529                "// continue \\\n"
2530                "formatMe();\n",
2531                "// st \\ art\\\n"
2532                "// comment"
2533                "// continue \\\n"
2534                "formatMe( );\n");
2535 }
2536 
2537 TEST_F(FormatTestJS, AddsLastLinePenaltyIfEndingIsBroken) {
2538   EXPECT_EQ(
2539       "a = function() {\n"
2540       "  b = function() {\n"
2541       "    this.aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa] = aaaa.aaaaaa ?\n"
2542       "        aaaa.aaaaaa : /** @type "
2543       "{aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaaaaaaaa} */\n"
2544       "        (aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaa);\n"
2545       "  };\n"
2546       "};",
2547       format("a = function() {\n"
2548              "  b = function() {\n"
2549              "    this.aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa] = aaaa.aaaaaa ? "
2550              "aaaa.aaaaaa : /** @type "
2551              "{aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaaaaaaaa} */\n"
2552              "        (aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaa);\n"
2553              "  };\n"
2554              "};"));
2555 }
2556 
2557 TEST_F(FormatTestJS, ParameterNamingComment) {
2558   verifyFormat("callFoo(/*spaceAfterParameterNamingComment=*/ 1);");
2559 }
2560 
2561 TEST_F(FormatTestJS, ConditionalTypes) {
2562   // Formatting below is not necessarily intentional, this just ensures that
2563   // clang-format does not break the code.
2564   verifyFormat( // wrap
2565       "type UnionToIntersection<U> =\n"
2566       "    (U extends any ? (k: U) => void :\n"
2567       "                     never) extends((k: infer I) => void) ? I : never;");
2568 }
2569 
2570 TEST_F(FormatTestJS, SupportPrivateFieldsAndMethods) {
2571   verifyFormat("class Example {\n"
2572                "  pub = 1;\n"
2573                "  #priv = 2;\n"
2574                "  static pub2 = 'foo';\n"
2575                "  static #priv2 = 'bar';\n"
2576                "  method() {\n"
2577                "    this.#priv = 5;\n"
2578                "  }\n"
2579                "  static staticMethod() {\n"
2580                "    switch (this.#priv) {\n"
2581                "      case '1':\n"
2582                "        #priv = 3;\n"
2583                "        break;\n"
2584                "    }\n"
2585                "  }\n"
2586                "  #privateMethod() {\n"
2587                "    this.#privateMethod();  // infinite loop\n"
2588                "  }\n"
2589                "  static #staticPrivateMethod() {}\n");
2590 }
2591 
2592 TEST_F(FormatTestJS, DeclaredFields) {
2593   verifyFormat("class Example {\n"
2594                "  declare pub: string;\n"
2595                "  declare private priv: string;\n"
2596                "}\n");
2597 }
2598 
2599 TEST_F(FormatTestJS, NoBreakAfterAsserts) {
2600   verifyFormat(
2601       "interface Assertable<State extends {}> {\n"
2602       "  assert<ExportedState extends {}, DependencyState extends State = "
2603       "State>(\n"
2604       "      callback: Callback<ExportedState, DependencyState>):\n"
2605       "      asserts this is ExtendedState<DependencyState&ExportedState>;\n"
2606       "}\n",
2607       "interface Assertable<State extends {}> {\n"
2608       "  assert<ExportedState extends {}, DependencyState extends State = "
2609       "State>(callback: Callback<ExportedState, DependencyState>): asserts "
2610       "this is ExtendedState<DependencyState&ExportedState>;\n"
2611       "}\n");
2612 }
2613 
2614 } // namespace format
2615 } // end namespace clang
2616