xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision c1631019a8cb0845d2f939613329d6210c7d4a2f)
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, AddsIsTheDictKeyOnNewline) {
1190   // Do not confuse is, the dict key with is, the type matcher. Put is, the dict
1191   // key, on a newline.
1192   verifyFormat("Polymer({\n"
1193                "  is: '',  //\n"
1194                "  rest: 1\n"
1195                "});",
1196                getGoogleJSStyleWithColumns(20));
1197 }
1198 
1199 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
1200   verifyFormat("a\n"
1201                "b;",
1202                " a \n"
1203                " b ;");
1204   verifyFormat("a()\n"
1205                "b;",
1206                " a ()\n"
1207                " b ;");
1208   verifyFormat("a[b]\n"
1209                "c;",
1210                "a [b]\n"
1211                "c ;");
1212   verifyFormat("1\n"
1213                "a;",
1214                "1 \n"
1215                "a ;");
1216   verifyFormat("a\n"
1217                "1;",
1218                "a \n"
1219                "1 ;");
1220   verifyFormat("a\n"
1221                "'x';",
1222                "a \n"
1223                " 'x';");
1224   verifyFormat("a++\n"
1225                "b;",
1226                "a ++\n"
1227                "b ;");
1228   verifyFormat("a\n"
1229                "!b && c;",
1230                "a \n"
1231                " ! b && c;");
1232   verifyFormat("a\n"
1233                "if (1) f();",
1234                " a\n"
1235                " if (1) f();");
1236   verifyFormat("a\n"
1237                "class X {}",
1238                " a\n"
1239                " class X {}");
1240   verifyFormat("var a", "var\n"
1241                         "a");
1242   verifyFormat("x instanceof String", "x\n"
1243                                       "instanceof\n"
1244                                       "String");
1245   verifyFormat("function f(@Foo bar) {}", "function f(@Foo\n"
1246                                           "  bar) {}");
1247   verifyFormat("function f(@Foo(Param) bar) {}", "function f(@Foo(Param)\n"
1248                                                  "  bar) {}");
1249   verifyFormat("a = true\n"
1250                "return 1",
1251                "a = true\n"
1252                "  return   1");
1253   verifyFormat("a = 's'\n"
1254                "return 1",
1255                "a = 's'\n"
1256                "  return   1");
1257   verifyFormat("a = null\n"
1258                "return 1",
1259                "a = null\n"
1260                "  return   1");
1261   // Below "class Y {}" should ideally be on its own line.
1262   verifyFormat(
1263       "x = {\n"
1264       "  a: 1\n"
1265       "} class Y {}",
1266       "  x  =  {a  : 1}\n"
1267       "   class  Y {  }");
1268   verifyFormat(
1269       "if (x) {\n"
1270       "}\n"
1271       "return 1",
1272       "if (x) {}\n"
1273       " return   1");
1274   verifyFormat(
1275       "if (x) {\n"
1276       "}\n"
1277       "class X {}",
1278       "if (x) {}\n"
1279       " class X {}");
1280 }
1281 
1282 TEST_F(FormatTestJS, ImportExportASI) {
1283   verifyFormat(
1284       "import {x} from 'y'\n"
1285       "export function z() {}",
1286       "import   {x} from 'y'\n"
1287       "  export function z() {}");
1288   // Below "class Y {}" should ideally be on its own line.
1289   verifyFormat(
1290       "export {x} class Y {}",
1291       "  export {x}\n"
1292       "  class  Y {\n}");
1293   verifyFormat(
1294       "if (x) {\n"
1295       "}\n"
1296       "export class Y {}",
1297       "if ( x ) { }\n"
1298       " export class Y {}");
1299 }
1300 
1301 TEST_F(FormatTestJS, ClosureStyleCasts) {
1302   verifyFormat("var x = /** @type {foo} */ (bar);");
1303 }
1304 
1305 TEST_F(FormatTestJS, TryCatch) {
1306   verifyFormat("try {\n"
1307                "  f();\n"
1308                "} catch (e) {\n"
1309                "  g();\n"
1310                "} finally {\n"
1311                "  h();\n"
1312                "}");
1313 
1314   // But, of course, "catch" is a perfectly fine function name in JavaScript.
1315   verifyFormat("someObject.catch();");
1316   verifyFormat("someObject.new();");
1317 }
1318 
1319 TEST_F(FormatTestJS, StringLiteralConcatenation) {
1320   verifyFormat("var literal = 'hello ' +\n"
1321                "    'world';");
1322 }
1323 
1324 TEST_F(FormatTestJS, RegexLiteralClassification) {
1325   // Regex literals.
1326   verifyFormat("var regex = /abc/;");
1327   verifyFormat("f(/abc/);");
1328   verifyFormat("f(abc, /abc/);");
1329   verifyFormat("some_map[/abc/];");
1330   verifyFormat("var x = a ? /abc/ : /abc/;");
1331   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
1332   verifyFormat("var x = !/abc/.test(y);");
1333   verifyFormat("var x = foo()! / 10;");
1334   verifyFormat("var x = a && /abc/.test(y);");
1335   verifyFormat("var x = a || /abc/.test(y);");
1336   verifyFormat("var x = a + /abc/.search(y);");
1337   verifyFormat("/abc/.search(y);");
1338   verifyFormat("var regexs = {/abc/, /abc/};");
1339   verifyFormat("return /abc/;");
1340 
1341   // Not regex literals.
1342   verifyFormat("var a = a / 2 + b / 3;");
1343   verifyFormat("var a = a++ / 2;");
1344   // Prefix unary can operate on regex literals, not that it makes sense.
1345   verifyFormat("var a = ++/a/;");
1346 
1347   // This is a known issue, regular expressions are incorrectly detected if
1348   // directly following a closing parenthesis.
1349   verifyFormat("if (foo) / bar /.exec(baz);");
1350 }
1351 
1352 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
1353   verifyFormat("var regex = /=/;");
1354   verifyFormat("var regex = /a*/;");
1355   verifyFormat("var regex = /a+/;");
1356   verifyFormat("var regex = /a?/;");
1357   verifyFormat("var regex = /.a./;");
1358   verifyFormat("var regex = /a\\*/;");
1359   verifyFormat("var regex = /^a$/;");
1360   verifyFormat("var regex = /\\/a/;");
1361   verifyFormat("var regex = /(?:x)/;");
1362   verifyFormat("var regex = /x(?=y)/;");
1363   verifyFormat("var regex = /x(?!y)/;");
1364   verifyFormat("var regex = /x|y/;");
1365   verifyFormat("var regex = /a{2}/;");
1366   verifyFormat("var regex = /a{1,3}/;");
1367 
1368   verifyFormat("var regex = /[abc]/;");
1369   verifyFormat("var regex = /[^abc]/;");
1370   verifyFormat("var regex = /[\\b]/;");
1371   verifyFormat("var regex = /[/]/;");
1372   verifyFormat("var regex = /[\\/]/;");
1373   verifyFormat("var regex = /\\[/;");
1374   verifyFormat("var regex = /\\\\[/]/;");
1375   verifyFormat("var regex = /}[\"]/;");
1376   verifyFormat("var regex = /}[/\"]/;");
1377   verifyFormat("var regex = /}[\"/]/;");
1378 
1379   verifyFormat("var regex = /\\b/;");
1380   verifyFormat("var regex = /\\B/;");
1381   verifyFormat("var regex = /\\d/;");
1382   verifyFormat("var regex = /\\D/;");
1383   verifyFormat("var regex = /\\f/;");
1384   verifyFormat("var regex = /\\n/;");
1385   verifyFormat("var regex = /\\r/;");
1386   verifyFormat("var regex = /\\s/;");
1387   verifyFormat("var regex = /\\S/;");
1388   verifyFormat("var regex = /\\t/;");
1389   verifyFormat("var regex = /\\v/;");
1390   verifyFormat("var regex = /\\w/;");
1391   verifyFormat("var regex = /\\W/;");
1392   verifyFormat("var regex = /a(a)\\1/;");
1393   verifyFormat("var regex = /\\0/;");
1394   verifyFormat("var regex = /\\\\/g;");
1395   verifyFormat("var regex = /\\a\\\\/g;");
1396   verifyFormat("var regex = /\a\\//g;");
1397   verifyFormat("var regex = /a\\//;\n"
1398                "var x = 0;");
1399   verifyFormat("var regex = /'/g;", "var regex = /'/g ;");
1400   verifyFormat("var regex = /'/g;  //'", "var regex = /'/g ; //'");
1401   verifyFormat("var regex = /\\/*/;\n"
1402                "var x = 0;",
1403                "var regex = /\\/*/;\n"
1404                "var x=0;");
1405   verifyFormat("var x = /a\\//;", "var x = /a\\//  \n;");
1406   verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
1407   verifyFormat("var regex =\n"
1408                "    /\"/;",
1409                getGoogleJSStyleWithColumns(15));
1410   verifyFormat("var regex =  //\n"
1411                "    /a/;");
1412   verifyFormat("var regexs = [\n"
1413                "  /d/,   //\n"
1414                "  /aa/,  //\n"
1415                "];");
1416 }
1417 
1418 TEST_F(FormatTestJS, RegexLiteralModifiers) {
1419   verifyFormat("var regex = /abc/g;");
1420   verifyFormat("var regex = /abc/i;");
1421   verifyFormat("var regex = /abc/m;");
1422   verifyFormat("var regex = /abc/y;");
1423 }
1424 
1425 TEST_F(FormatTestJS, RegexLiteralLength) {
1426   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1427                getGoogleJSStyleWithColumns(60));
1428   verifyFormat("var regex =\n"
1429                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1430                getGoogleJSStyleWithColumns(60));
1431   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1432                getGoogleJSStyleWithColumns(50));
1433 }
1434 
1435 TEST_F(FormatTestJS, RegexLiteralExamples) {
1436   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
1437 }
1438 
1439 TEST_F(FormatTestJS, IgnoresMpegTS) {
1440   std::string MpegTS(200, ' ');
1441   MpegTS.replace(0, strlen("nearlyLooks  +   like +   ts + code;  "),
1442                  "nearlyLooks  +   like +   ts + code;  ");
1443   MpegTS[0] = 0x47;
1444   MpegTS[188] = 0x47;
1445   verifyFormat(MpegTS, MpegTS);
1446 }
1447 
1448 TEST_F(FormatTestJS, TypeAnnotations) {
1449   verifyFormat("var x: string;");
1450   verifyFormat("var x: {a: string; b: number;} = {};");
1451   verifyFormat("function x(): string {\n  return 'x';\n}");
1452   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
1453   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
1454   verifyFormat("for (var y: string in x) {\n  x();\n}");
1455   verifyFormat("for (var y: string of x) {\n  x();\n}");
1456   verifyFormat("function x(y: {a?: number;} = {}): number {\n"
1457                "  return 12;\n"
1458                "}");
1459   verifyFormat("const x: Array<{a: number; b: string;}> = [];");
1460   verifyFormat("((a: string, b: number): string => a + b);");
1461   verifyFormat("var x: (y: number) => string;");
1462   verifyFormat("var x: P<string, (a: number) => string>;");
1463   verifyFormat("var x = {\n"
1464                "  y: function(): z {\n"
1465                "    return 1;\n"
1466                "  }\n"
1467                "};");
1468   verifyFormat("var x = {\n"
1469                "  y: function(): {a: number} {\n"
1470                "    return 1;\n"
1471                "  }\n"
1472                "};");
1473   verifyFormat("function someFunc(args: string[]):\n"
1474                "    {longReturnValue: string[]} {}",
1475                getGoogleJSStyleWithColumns(60));
1476   verifyFormat(
1477       "var someValue = (v as aaaaaaaaaaaaaaaaaaaa<T>[])\n"
1478       "                    .someFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1479   verifyFormat("const xIsALongIdent:\n""    YJustBarelyFitsLinex[];",
1480       getGoogleJSStyleWithColumns(20));
1481 }
1482 
1483 TEST_F(FormatTestJS, UnionIntersectionTypes) {
1484   verifyFormat("let x: A|B = A | B;");
1485   verifyFormat("let x: A&B|C = A & B;");
1486   verifyFormat("let x: Foo<A|B> = new Foo<A|B>();");
1487   verifyFormat("function(x: A|B): C&D {}");
1488   verifyFormat("function(x: A|B = A | B): C&D {}");
1489   verifyFormat("function x(path: number|string) {}");
1490   verifyFormat("function x(): string|number {}");
1491   verifyFormat("type Foo = Bar|Baz;");
1492   verifyFormat("type Foo = Bar<X>|Baz;");
1493   verifyFormat("type Foo = (Bar<X>|Baz);");
1494   verifyFormat("let x: Bar|Baz;");
1495   verifyFormat("let x: Bar<X>|Baz;");
1496   verifyFormat("let x: (Foo|Bar)[];");
1497   verifyFormat("type X = {\n"
1498                "  a: Foo|Bar;\n"
1499                "};");
1500   verifyFormat("export type X = {\n"
1501                "  a: Foo|Bar;\n"
1502                "};");
1503 }
1504 
1505 TEST_F(FormatTestJS, UnionIntersectionTypesInObjectType) {
1506   verifyFormat("let x: {x: number|null} = {x: number | null};");
1507   verifyFormat("let nested: {x: {y: number|null}};");
1508   verifyFormat("let mixed: {x: [number|null, {w: number}]};");
1509   verifyFormat("class X {\n"
1510                "  contructor(x: {\n"
1511                "    a: a|null,\n"
1512                "    b: b|null,\n"
1513                "  }) {}\n"
1514                "}");
1515 }
1516 
1517 TEST_F(FormatTestJS, ClassDeclarations) {
1518   verifyFormat("class C {\n  x: string = 12;\n}");
1519   verifyFormat("class C {\n  x(): string => 12;\n}");
1520   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
1521   verifyFormat("class C {\n"
1522                "  foo() {}\n"
1523                "  [bar]() {}\n"
1524                "}\n");
1525   verifyFormat("class C {\n  private x: string = 12;\n}");
1526   verifyFormat("class C {\n  private static x: string = 12;\n}");
1527   verifyFormat("class C {\n  static x(): string {\n    return 'asd';\n  }\n}");
1528   verifyFormat("class C extends P implements I {}");
1529   verifyFormat("class C extends p.P implements i.I {}");
1530   verifyFormat(
1531       "x(class {\n"
1532       "  a(): A {}\n"
1533       "});");
1534   verifyFormat("class Test {\n"
1535                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
1536                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
1537                "}");
1538   verifyFormat("foo = class Name {\n"
1539                "  constructor() {}\n"
1540                "};");
1541   verifyFormat("foo = class {\n"
1542                "  constructor() {}\n"
1543                "};");
1544   verifyFormat("class C {\n"
1545                "  x: {y: Z;} = {};\n"
1546                "  private y: {y: Z;} = {};\n"
1547                "}");
1548 
1549   // ':' is not a type declaration here.
1550   verifyFormat("class X {\n"
1551                "  subs = {\n"
1552                "    'b': {\n"
1553                "      'c': 1,\n"
1554                "    },\n"
1555                "  };\n"
1556                "}");
1557   verifyFormat("@Component({\n"
1558                "  moduleId: module.id,\n"
1559                "})\n"
1560                "class SessionListComponent implements OnDestroy, OnInit {\n"
1561                "}");
1562 }
1563 
1564 TEST_F(FormatTestJS, StrictPropInitWrap) {
1565   const FormatStyle &Style = getGoogleJSStyleWithColumns(22);
1566   verifyFormat("class X {\n"
1567                "  strictPropInitField!:\n"
1568                "      string;\n"
1569                "}",
1570                Style);
1571 }
1572 
1573 TEST_F(FormatTestJS, InterfaceDeclarations) {
1574   verifyFormat("interface I {\n"
1575                "  x: string;\n"
1576                "  enum: string[];\n"
1577                "  enum?: string[];\n"
1578                "}\n"
1579                "var y;");
1580   // Ensure that state is reset after parsing the interface.
1581   verifyFormat("interface a {}\n"
1582                "export function b() {}\n"
1583                "var x;");
1584 
1585   // Arrays of object type literals.
1586   verifyFormat("interface I {\n"
1587                "  o: {}[];\n"
1588                "}");
1589 }
1590 
1591 TEST_F(FormatTestJS, ObjectTypesInExtendsImplements) {
1592   verifyFormat("class C extends {} {}");
1593   verifyFormat("class C implements {bar: number} {}");
1594   // Somewhat odd, but probably closest to reasonable formatting?
1595   verifyFormat("class C implements {\n"
1596                "  bar: number,\n"
1597                "  baz: string,\n"
1598                "} {}");
1599   verifyFormat("class C<P extends {}> {}");
1600 }
1601 
1602 TEST_F(FormatTestJS, EnumDeclarations) {
1603   verifyFormat("enum Foo {\n"
1604                "  A = 1,\n"
1605                "  B\n"
1606                "}");
1607   verifyFormat("export /* somecomment*/ enum Foo {\n"
1608                "  A = 1,\n"
1609                "  B\n"
1610                "}");
1611   verifyFormat("enum Foo {\n"
1612                "  A = 1,  // comment\n"
1613                "  B\n"
1614                "}\n"
1615                "var x = 1;");
1616   verifyFormat("const enum Foo {\n"
1617                "  A = 1,\n"
1618                "  B\n"
1619                "}");
1620   verifyFormat("export const enum Foo {\n"
1621                "  A = 1,\n"
1622                "  B\n"
1623                "}");
1624 }
1625 
1626 TEST_F(FormatTestJS, Decorators) {
1627   verifyFormat("@A\nclass C {\n}");
1628   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
1629   verifyFormat("@A\n@B\nclass C {\n}");
1630   verifyFormat("class C {\n  @A x: string;\n}");
1631   verifyFormat("class C {\n"
1632                "  @A\n"
1633                "  private x(): string {\n"
1634                "    return 'y';\n"
1635                "  }\n"
1636                "}");
1637   verifyFormat("class C {\n"
1638                "  private x(@A x: string) {}\n"
1639                "}");
1640   verifyFormat("class X {}\n"
1641                "class Y {}");
1642   verifyFormat("class X {\n"
1643                "  @property() private isReply = false;\n"
1644                "}\n");
1645 }
1646 
1647 TEST_F(FormatTestJS, TypeAliases) {
1648   verifyFormat("type X = number;\n"
1649                "class C {}");
1650   verifyFormat("type X<Y> = Z<Y>;");
1651   verifyFormat("type X = {\n"
1652                "  y: number\n"
1653                "};\n"
1654                "class C {}");
1655   verifyFormat("export type X = {\n"
1656                "  a: string,\n"
1657                "  b?: string,\n"
1658                "};\n");
1659 }
1660 
1661 TEST_F(FormatTestJS, TypeInterfaceLineWrapping) {
1662   const FormatStyle &Style = getGoogleJSStyleWithColumns(20);
1663   verifyFormat("type LongTypeIsReallyUnreasonablyLong =\n"
1664                "    string;\n",
1665                "type LongTypeIsReallyUnreasonablyLong = string;\n",
1666                Style);
1667   verifyFormat(
1668       "interface AbstractStrategyFactoryProvider {\n"
1669       "  a: number\n"
1670       "}\n",
1671       "interface AbstractStrategyFactoryProvider { a: number }\n",
1672       Style);
1673 }
1674 
1675 TEST_F(FormatTestJS, RemoveEmptyLinesInArrowFunctions) {
1676   verifyFormat("x = () => {\n"
1677                "  foo();\n"
1678                "};\n",
1679                "x = () => {\n"
1680                "\n"
1681                "  foo();\n"
1682                "\n"
1683                "};\n");
1684 }
1685 
1686 TEST_F(FormatTestJS, Modules) {
1687   verifyFormat("import SomeThing from 'some/module.js';");
1688   verifyFormat("import {X, Y} from 'some/module.js';");
1689   verifyFormat("import a, {X, Y} from 'some/module.js';");
1690   verifyFormat("import {X, Y,} from 'some/module.js';");
1691   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
1692   // Ensure Automatic Semicolon Insertion does not break on "as\n".
1693   verifyFormat("import {X as myX} from 'm';", "import {X as\n"
1694                                               " myX} from 'm';");
1695   verifyFormat("import * as lib from 'some/module.js';");
1696   verifyFormat("var x = {import: 1};\nx.import = 2;");
1697 
1698   verifyFormat("export function fn() {\n"
1699                "  return 'fn';\n"
1700                "}");
1701   verifyFormat("export function A() {}\n"
1702                "export default function B() {}\n"
1703                "export function C() {}");
1704   verifyFormat("export default () => {\n"
1705                "  let x = 1;\n"
1706                "  return x;\n"
1707                "}");
1708   verifyFormat("export const x = 12;");
1709   verifyFormat("export default class X {}");
1710   verifyFormat("export {X, Y} from 'some/module.js';");
1711   verifyFormat("export {X, Y,} from 'some/module.js';");
1712   verifyFormat("export {SomeVeryLongExport as X, "
1713                "SomeOtherVeryLongExport as Y} from 'some/module.js';");
1714   // export without 'from' is wrapped.
1715   verifyFormat("export let someRatherLongVariableName =\n"
1716                "    someSurprisinglyLongVariable + someOtherRatherLongVar;");
1717   // ... but not if from is just an identifier.
1718   verifyFormat("export {\n"
1719                "  from as from,\n"
1720                "  someSurprisinglyLongVariable as\n"
1721                "      from\n"
1722                "};",
1723                getGoogleJSStyleWithColumns(20));
1724   verifyFormat("export class C {\n"
1725                "  x: number;\n"
1726                "  y: string;\n"
1727                "}");
1728   verifyFormat("export class X {\n"
1729                "  y: number;\n"
1730                "}");
1731   verifyFormat("export abstract class X {\n"
1732                "  y: number;\n"
1733                "}");
1734   verifyFormat("export default class X {\n"
1735                "  y: number\n"
1736                "}");
1737   verifyFormat("export default function() {\n  return 1;\n}");
1738   verifyFormat("export var x = 12;");
1739   verifyFormat("class C {}\n"
1740                "export function f() {}\n"
1741                "var v;");
1742   verifyFormat("export var x: number = 12;");
1743   verifyFormat("export const y = {\n"
1744                "  a: 1,\n"
1745                "  b: 2\n"
1746                "};");
1747   verifyFormat("export enum Foo {\n"
1748                "  BAR,\n"
1749                "  // adsdasd\n"
1750                "  BAZ\n"
1751                "}");
1752   verifyFormat("export default [\n"
1753                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1754                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
1755                "];");
1756   verifyFormat("export default [];");
1757   verifyFormat("export default () => {};");
1758   verifyFormat("export interface Foo {\n"
1759                "  foo: number;\n"
1760                "}\n"
1761                "export class Bar {\n"
1762                "  blah(): string {\n"
1763                "    return this.blah;\n"
1764                "  };\n"
1765                "}");
1766 }
1767 
1768 TEST_F(FormatTestJS, ImportWrapping) {
1769   verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
1770                " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
1771                "} from 'some/module.js';");
1772   FormatStyle Style = getGoogleJSStyleWithColumns(80);
1773   Style.JavaScriptWrapImports = true;
1774   verifyFormat("import {\n"
1775                "  VeryLongImportsAreAnnoying,\n"
1776                "  VeryLongImportsAreAnnoying,\n"
1777                "  VeryLongImportsAreAnnoying,\n"
1778                "} from 'some/module.js';",
1779                Style);
1780   verifyFormat("import {\n"
1781                "  A,\n"
1782                "  A,\n"
1783                "} from 'some/module.js';",
1784                Style);
1785   verifyFormat("export {\n"
1786                "  A,\n"
1787                "  A,\n"
1788                "} from 'some/module.js';",
1789                Style);
1790   Style.ColumnLimit = 40;
1791   // Using this version of verifyFormat because test::messUp hides the issue.
1792   verifyFormat("import {\n"
1793                "  A,\n"
1794                "} from\n"
1795                "    'some/path/longer/than/column/limit/module.js';",
1796                " import  {  \n"
1797                "    A,  \n"
1798                "  }    from\n"
1799                "      'some/path/longer/than/column/limit/module.js'  ; ",
1800                Style);
1801 }
1802 
1803 TEST_F(FormatTestJS, TemplateStrings) {
1804   // Keeps any whitespace/indentation within the template string.
1805   verifyFormat("var x = `hello\n"
1806             "     ${name}\n"
1807             "  !`;",
1808             "var x    =    `hello\n"
1809                    "     ${  name    }\n"
1810                    "  !`;");
1811 
1812   verifyFormat("var x =\n"
1813                "    `hello ${world}` >= some();",
1814                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
1815   verifyFormat("var x = `hello ${world}` >= some();",
1816                getGoogleJSStyleWithColumns(35)); // Barely fits.
1817   verifyFormat("var x = `hellö ${wörld}` >= söme();",
1818                getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8.
1819   verifyFormat("var x = `hello\n"
1820             "  ${world}` >=\n"
1821             "    some();",
1822             "var x =\n"
1823                    "    `hello\n"
1824                    "  ${world}` >= some();",
1825                    getGoogleJSStyleWithColumns(21)); // Barely doesn't fit.
1826   verifyFormat("var x = `hello\n"
1827             "  ${world}` >= some();",
1828             "var x =\n"
1829                    "    `hello\n"
1830                    "  ${world}` >= some();",
1831                    getGoogleJSStyleWithColumns(22)); // Barely fits.
1832 
1833   verifyFormat("var x =\n"
1834                "    `h`;",
1835                getGoogleJSStyleWithColumns(11));
1836   verifyFormat("var x =\n    `multi\n  line`;", "var x = `multi\n  line`;",
1837                getGoogleJSStyleWithColumns(13));
1838   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1839                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
1840   // Repro for an obscure width-miscounting issue with template strings.
1841   verifyFormat(
1842       "someLongVariable =\n"
1843       "    "
1844       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;",
1845       "someLongVariable = "
1846       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;");
1847 
1848   // Make sure template strings get a proper ColumnWidth assigned, even if they
1849   // are first token in line.
1850   verifyFormat(
1851       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1852       "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
1853 
1854   // Two template strings.
1855   verifyFormat("var x = `hello` == `hello`;");
1856 
1857   // Comments in template strings.
1858   verifyFormat("var x = `//a`;\n"
1859             "var y;",
1860             "var x =\n `//a`;\n"
1861                    "var y  ;");
1862   verifyFormat("var x = `/*a`;\n"
1863                "var y;",
1864                "var x =\n `/*a`;\n"
1865                "var y;");
1866   // Unterminated string literals in a template string.
1867   verifyFormat("var x = `'`;  // comment with matching quote '\n"
1868                "var y;");
1869   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
1870                "var y;");
1871   verifyFormat("it(`'aaaaaaaaaaaaaaa   `, aaaaaaaaa);",
1872                "it(`'aaaaaaaaaaaaaaa   `,   aaaaaaaaa) ;",
1873                getGoogleJSStyleWithColumns(40));
1874   // Backticks in a comment - not a template string.
1875   verifyFormat("var x = 1  // `/*a`;\n"
1876                "    ;",
1877                "var x =\n 1  // `/*a`;\n"
1878                "    ;");
1879   verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */");
1880   // Comment spans multiple template strings.
1881   verifyFormat("var x = `/*a`;\n"
1882                "var y = ` */ `;",
1883                "var x =\n `/*a`;\n"
1884                "var y =\n ` */ `;");
1885   // Escaped backtick.
1886   verifyFormat("var x = ` \\` a`;\n"
1887                "var y;",
1888                "var x = ` \\` a`;\n"
1889                "var y;");
1890   // Escaped dollar.
1891   verifyFormat("var x = ` \\${foo}`;\n");
1892 
1893   // The token stream can contain two string_literals in sequence, but that
1894   // doesn't mean that they are implicitly concatenated in JavaScript.
1895   verifyFormat("var f = `aaaa ${a ? 'a' : 'b'}`;");
1896 
1897   // Ensure that scopes are appropriately set around evaluated expressions in
1898   // template strings.
1899   verifyFormat("var f = `aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa\n"
1900                "         aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`;",
1901                "var f = `aaaaaaaaaaaaa:${aaaaaaa.  aaaaa} aaaaaaaa\n"
1902                "         aaaaaaaaaaaaa:${  aaaaaaa. aaaaa} aaaaaaaa`;");
1903   verifyFormat("var x = someFunction(`${})`)  //\n"
1904                "            .oooooooooooooooooon();");
1905   verifyFormat("var x = someFunction(`${aaaa}${\n"
1906                "    aaaaa(  //\n"
1907                "        aaaaa)})`);");
1908 }
1909 
1910 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) {
1911   verifyFormat("var f = `aaaaaaaaaaaaaaaaaa: ${\n"
1912                "    aaaaa +  //\n"
1913                "    bbbb}`;",
1914                "var f = `aaaaaaaaaaaaaaaaaa: ${aaaaa +  //\n"
1915                "                               bbbb}`;");
1916   verifyFormat("var f = `\n"
1917                "  aaaaaaaaaaaaaaaaaa: ${\n"
1918                "    aaaaa +  //\n"
1919                "    bbbb}`;",
1920                "var f  =  `\n"
1921                "  aaaaaaaaaaaaaaaaaa: ${   aaaaa  +  //\n"
1922                "                        bbbb }`;");
1923   verifyFormat("var f = `\n"
1924                "  aaaaaaaaaaaaaaaaaa: ${\n"
1925                "    someFunction(\n"
1926                "        aaaaa +  //\n"
1927                "        bbbb)}`;",
1928                "var f  =  `\n"
1929                "  aaaaaaaaaaaaaaaaaa: ${someFunction (\n"
1930                "                            aaaaa  +   //\n"
1931                "                            bbbb)}`;");
1932 
1933   // It might be preferable to wrap before "someFunction".
1934   verifyFormat("var f = `\n"
1935                "  aaaaaaaaaaaaaaaaaa: ${someFunction({\n"
1936                "  aaaa: aaaaa,\n"
1937                "  bbbb: bbbbb,\n"
1938                "})}`;",
1939                "var f  =  `\n"
1940                "  aaaaaaaaaaaaaaaaaa: ${someFunction ({\n"
1941                "                          aaaa:  aaaaa,\n"
1942                "                          bbbb:  bbbbb,\n"
1943                "                        })}`;");
1944 }
1945 
1946 TEST_F(FormatTestJS, TemplateStringASI) {
1947   verifyFormat("var x = `hello${world}`;", "var x = `hello${\n"
1948                                            "    world\n"
1949                                            "}`;");
1950 }
1951 
1952 TEST_F(FormatTestJS, NestedTemplateStrings) {
1953   verifyFormat(
1954       "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;");
1955   verifyFormat("var x = `he${({text: 'll'}.text)}o`;");
1956 
1957   // Crashed at some point.
1958   verifyFormat("}");
1959 }
1960 
1961 TEST_F(FormatTestJS, TaggedTemplateStrings) {
1962   verifyFormat("var x = html`<ul>`;");
1963   verifyFormat("yield `hello`;");
1964 }
1965 
1966 TEST_F(FormatTestJS, CastSyntax) {
1967   verifyFormat("var x = <type>foo;");
1968   verifyFormat("var x = foo as type;");
1969   verifyFormat("let x = (a + b) as\n"
1970                "    LongTypeIsLong;",
1971                getGoogleJSStyleWithColumns(20));
1972   verifyFormat("foo = <Bar[]>[\n"
1973                "  1,  //\n"
1974                "  2\n"
1975                "];");
1976   verifyFormat("var x = [{x: 1} as type];");
1977   verifyFormat("x = x as [a, b];");
1978   verifyFormat("x = x as {a: string};");
1979   verifyFormat("x = x as (string);");
1980   verifyFormat("x = x! as (string);");
1981   verifyFormat("x = y! in z;");
1982   verifyFormat("var x = something.someFunction() as\n"
1983                "    something;",
1984                getGoogleJSStyleWithColumns(40));
1985 }
1986 
1987 TEST_F(FormatTestJS, TypeArguments) {
1988   verifyFormat("class X<Y> {}");
1989   verifyFormat("new X<Y>();");
1990   verifyFormat("foo<Y>(a);");
1991   verifyFormat("var x: X<Y>[];");
1992   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
1993   verifyFormat("function f(a: List<any> = null) {}");
1994   verifyFormat("function f(): List<any> {}");
1995   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
1996                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
1997   verifyFormat("function aaaaaaaaaa(\n"
1998                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
1999                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
2000                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
2001 }
2002 
2003 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
2004   verifyFormat(
2005       "function foo(check: Object):\n"
2006       "    check is {foo: string, bar: string, baz: string, foobar: string} {\n"
2007       "  return 'bar' in check;\n"
2008       "}\n");
2009 }
2010 
2011 TEST_F(FormatTestJS, OptionalTypes) {
2012   verifyFormat("function x(a?: b, c?, d?) {}");
2013   verifyFormat("class X {\n"
2014                "  y?: z;\n"
2015                "  z?;\n"
2016                "}");
2017   verifyFormat("interface X {\n"
2018                "  y?(): z;\n"
2019                "}");
2020   verifyFormat("constructor({aa}: {\n"
2021                "  aa?: string,\n"
2022                "  aaaaaaaa?: string,\n"
2023                "  aaaaaaaaaaaaaaa?: boolean,\n"
2024                "  aaaaaa?: List<string>\n"
2025                "}) {}");
2026 }
2027 
2028 TEST_F(FormatTestJS, IndexSignature) {
2029   verifyFormat("var x: {[k: string]: v};");
2030 }
2031 
2032 TEST_F(FormatTestJS, WrapAfterParen) {
2033   verifyFormat("xxxxxxxxxxx(\n"
2034                "    aaa, aaa);",
2035                getGoogleJSStyleWithColumns(20));
2036   verifyFormat("xxxxxxxxxxx(\n"
2037                "    aaa, aaa, aaa,\n"
2038                "    aaa, aaa, aaa);",
2039                getGoogleJSStyleWithColumns(20));
2040   verifyFormat("xxxxxxxxxxx(\n"
2041                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
2042                "    function(x) {\n"
2043                "      y();  //\n"
2044                "    });",
2045                getGoogleJSStyleWithColumns(40));
2046   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
2047                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2048 }
2049 
2050 TEST_F(FormatTestJS, JSDocAnnotations) {
2051   verifyFormat("/**\n"
2052                " * @exports {this.is.a.long.path.to.a.Type}\n"
2053                " */",
2054                "/**\n"
2055                " * @exports {this.is.a.long.path.to.a.Type}\n"
2056                " */",
2057                getGoogleJSStyleWithColumns(20));
2058   verifyFormat("/**\n"
2059                " * @mods {this.is.a.long.path.to.a.Type}\n"
2060                " */",
2061                "/**\n"
2062                " * @mods {this.is.a.long.path.to.a.Type}\n"
2063                " */",
2064                getGoogleJSStyleWithColumns(20));
2065   verifyFormat("/**\n"
2066                " * @mods {this.is.a.long.path.to.a.Type}\n"
2067                " */",
2068                "/**\n"
2069                " * @mods {this.is.a.long.path.to.a.Type}\n"
2070                " */",
2071                getGoogleJSStyleWithColumns(20));
2072   verifyFormat("/**\n"
2073                " * @param {canWrap\n"
2074                " *     onSpace}\n"
2075                " */",
2076                "/**\n"
2077                " * @param {canWrap onSpace}\n"
2078                " */",
2079                getGoogleJSStyleWithColumns(20));
2080   // make sure clang-format doesn't break before *any* '{'
2081   verifyFormat("/**\n"
2082                " * @lala {lala {lalala\n"
2083                " */\n",
2084                "/**\n"
2085                " * @lala {lala {lalala\n"
2086                " */\n",
2087                getGoogleJSStyleWithColumns(20));
2088   verifyFormat("/**\n"
2089                " * @see http://very/very/long/url/is/long\n"
2090                " */",
2091                "/**\n"
2092                " * @see http://very/very/long/url/is/long\n"
2093                " */",
2094                getGoogleJSStyleWithColumns(20));
2095   verifyFormat(
2096       "/**\n"
2097       " * @param This is a\n"
2098       " *     long comment\n"
2099       " *     but no type\n"
2100       " */",
2101       "/**\n"
2102       " * @param This is a long comment but no type\n"
2103       " */",
2104       getGoogleJSStyleWithColumns(20));
2105   // Break and reindent @param line and reflow unrelated lines.
2106   EXPECT_EQ("{\n"
2107             "  /**\n"
2108             "   * long long long\n"
2109             "   * long\n"
2110             "   * @param {this.is.a.long.path.to.a.Type}\n"
2111             "   *     a\n"
2112             "   * long long long\n"
2113             "   * long long\n"
2114             "   */\n"
2115             "  function f(a) {}\n"
2116             "}",
2117             format("{\n"
2118                    "/**\n"
2119                    " * long long long long\n"
2120                    " * @param {this.is.a.long.path.to.a.Type} a\n"
2121                    " * long long long long\n"
2122                    " * long\n"
2123                    " */\n"
2124                    "  function f(a) {}\n"
2125                    "}",
2126                    getGoogleJSStyleWithColumns(20)));
2127 }
2128 
2129 TEST_F(FormatTestJS, RequoteStringsSingle) {
2130   verifyFormat("var x = 'foo';", "var x = \"foo\";");
2131   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";");
2132   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";");
2133   verifyFormat(
2134       "var x =\n"
2135       "    'foo\\'';",
2136       // Code below is 15 chars wide, doesn't fit into the line with the
2137       // \ escape added.
2138       "var x = \"foo'\";", getGoogleJSStyleWithColumns(15));
2139   // Removes no-longer needed \ escape from ".
2140   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";");
2141   // Code below fits into 15 chars *after* removing the \ escape.
2142   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";",
2143                getGoogleJSStyleWithColumns(15));
2144   verifyFormat("// clang-format off\n"
2145                "let x = \"double\";\n"
2146                "// clang-format on\n"
2147                "let x = 'single';\n",
2148                "// clang-format off\n"
2149                "let x = \"double\";\n"
2150                "// clang-format on\n"
2151                "let x = \"single\";\n");
2152 }
2153 
2154 TEST_F(FormatTestJS, RequoteAndIndent) {
2155   verifyFormat("let x = someVeryLongFunctionThatGoesOnAndOn(\n"
2156                "    'double quoted string that needs wrapping');",
2157                "let x = someVeryLongFunctionThatGoesOnAndOn("
2158                "\"double quoted string that needs wrapping\");");
2159 
2160   verifyFormat("let x =\n"
2161                "    'foo\\'oo';\n"
2162                "let x =\n"
2163                "    'foo\\'oo';",
2164                "let x=\"foo'oo\";\n"
2165                "let x=\"foo'oo\";",
2166                getGoogleJSStyleWithColumns(15));
2167 }
2168 
2169 TEST_F(FormatTestJS, RequoteStringsDouble) {
2170   FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2171   DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double;
2172   verifyFormat("var x = \"foo\";", DoubleQuotes);
2173   verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes);
2174   verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes);
2175 }
2176 
2177 TEST_F(FormatTestJS, RequoteStringsLeave) {
2178   FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2179   LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave;
2180   verifyFormat("var x = \"foo\";", LeaveQuotes);
2181   verifyFormat("var x = 'foo';", LeaveQuotes);
2182 }
2183 
2184 TEST_F(FormatTestJS, SupportShebangLines) {
2185   verifyFormat("#!/usr/bin/env node\n"
2186                "var x = hello();",
2187                "#!/usr/bin/env node\n"
2188                "var x   =  hello();");
2189 }
2190 
2191 TEST_F(FormatTestJS, NonNullAssertionOperator) {
2192   verifyFormat("let x = foo!.bar();\n");
2193   verifyFormat("let x = foo ? bar! : baz;\n");
2194   verifyFormat("let x = !foo;\n");
2195   verifyFormat("if (!+a) {\n}");
2196   verifyFormat("let x = foo[0]!;\n");
2197   verifyFormat("let x = (foo)!;\n");
2198   verifyFormat("let x = x(foo!);\n");
2199   verifyFormat(
2200       "a.aaaaaa(a.a!).then(\n"
2201       "    x => x(x));\n",
2202       getGoogleJSStyleWithColumns(20));
2203   verifyFormat("let x = foo! - 1;\n");
2204   verifyFormat("let x = {foo: 1}!;\n");
2205   verifyFormat(
2206       "let x = hello.foo()!\n"
2207       "            .foo()!\n"
2208       "            .foo()!\n"
2209       "            .foo()!;\n",
2210       getGoogleJSStyleWithColumns(20));
2211   verifyFormat("let x = namespace!;\n");
2212   verifyFormat("return !!x;\n");
2213 }
2214 
2215 TEST_F(FormatTestJS, Conditional) {
2216   verifyFormat("y = x ? 1 : 2;");
2217   verifyFormat("x ? 1 : 2;");
2218   verifyFormat("class Foo {\n"
2219                "  field = true ? 1 : 2;\n"
2220                "  method(a = true ? 1 : 2) {}\n"
2221                "}");
2222 }
2223 
2224 TEST_F(FormatTestJS, ImportComments) {
2225   verifyFormat("import {x} from 'x';  // from some location",
2226                getGoogleJSStyleWithColumns(25));
2227   verifyFormat("// taze: x from 'location'", getGoogleJSStyleWithColumns(10));
2228   verifyFormat("/// <reference path=\"some/location\" />", getGoogleJSStyleWithColumns(10));
2229 }
2230 
2231 TEST_F(FormatTestJS, Exponentiation) {
2232   verifyFormat("squared = x ** 2;");
2233   verifyFormat("squared **= 2;");
2234 }
2235 
2236 TEST_F(FormatTestJS, NestedLiterals) {
2237   FormatStyle FourSpaces = getGoogleJSStyleWithColumns(15);
2238   FourSpaces.IndentWidth = 4;
2239   verifyFormat("var l = [\n"
2240                "    [\n"
2241                "        1,\n"
2242                "    ],\n"
2243                "];", FourSpaces);
2244   verifyFormat("var l = [\n"
2245                "    {\n"
2246                "        1: 1,\n"
2247                "    },\n"
2248                "];", FourSpaces);
2249   verifyFormat("someFunction(\n"
2250                "    p1,\n"
2251                "    [\n"
2252                "        1,\n"
2253                "    ],\n"
2254                ");", FourSpaces);
2255   verifyFormat("someFunction(\n"
2256                "    p1,\n"
2257                "    {\n"
2258                "        1: 1,\n"
2259                "    },\n"
2260                ");", FourSpaces);
2261   verifyFormat("var o = {\n"
2262                "    1: 1,\n"
2263                "    2: {\n"
2264                "        3: 3,\n"
2265                "    },\n"
2266                "};", FourSpaces);
2267   verifyFormat("var o = {\n"
2268                "    1: 1,\n"
2269                "    2: [\n"
2270                "        3,\n"
2271                "    ],\n"
2272                "};", FourSpaces);
2273 }
2274 
2275 TEST_F(FormatTestJS, BackslashesInComments) {
2276   verifyFormat("// hello \\\n"
2277                "if (x) foo();\n",
2278                "// hello \\\n"
2279                "     if ( x) \n"
2280                "   foo();\n");
2281   verifyFormat("/* ignore \\\n"
2282                " */\n"
2283                "if (x) foo();\n",
2284                "/* ignore \\\n"
2285                " */\n"
2286                " if (  x) foo();\n");
2287   verifyFormat("// st \\ art\\\n"
2288                "// comment"
2289                "// continue \\\n"
2290                "formatMe();\n",
2291                "// st \\ art\\\n"
2292                "// comment"
2293                "// continue \\\n"
2294                "formatMe( );\n");
2295 }
2296 
2297 TEST_F(FormatTestJS, AddsLastLinePenaltyIfEndingIsBroken) {
2298   EXPECT_EQ(
2299       "a = function() {\n"
2300       "  b = function() {\n"
2301       "    this.aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa] = aaaa.aaaaaa ?\n"
2302       "        aaaa.aaaaaa : /** @type "
2303       "{aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaaaaaaaa} */\n"
2304       "        (aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaa);\n"
2305       "  };\n"
2306       "};",
2307       format("a = function() {\n"
2308              "  b = function() {\n"
2309              "    this.aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa] = aaaa.aaaaaa ? "
2310              "aaaa.aaaaaa : /** @type "
2311              "{aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaaaaaaaa} */\n"
2312              "        (aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaa);\n"
2313              "  };\n"
2314              "};"));
2315 }
2316 
2317 TEST_F(FormatTestJS, ParameterNamingComment) {
2318   verifyFormat("callFoo(/*spaceAfterParameterNamingComment=*/ 1);");
2319 }
2320 
2321 TEST_F(FormatTestJS, ConditionalTypes) {
2322   // Formatting below is not necessarily intentional, this just ensures that
2323   // clang-format does not break the code.
2324   verifyFormat( // wrap
2325       "type UnionToIntersection<U> =\n"
2326       "    (U extends any ? (k: U) => void :\n"
2327       "                     never) extends((k: infer I) => void) ? I : never;");
2328 }
2329 
2330 } // end namespace tooling
2331 } // end namespace clang
2332