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