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