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