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