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