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("const X = goog.requireType('this.is.really.absurdly.long');",
604                getGoogleJSStyleWithColumns(40));
605   verifyFormat("goog.forwardDeclare('this.is.really.absurdly.long');",
606                getGoogleJSStyleWithColumns(40));
607 
608   // These should be wrapped normally.
609   verifyFormat(
610       "var MyLongClassName =\n"
611       "    goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
612   verifyFormat("function a() {\n"
613                "  goog.setTestOnly();\n"
614                "}\n",
615                "function a() {\n"
616                "goog.setTestOnly();\n"
617                "}\n");
618 }
619 
620 TEST_F(FormatTestJS, FormatsNamespaces) {
621   verifyFormat("namespace Foo {\n"
622                "  export let x = 1;\n"
623                "}\n");
624   verifyFormat("declare namespace Foo {\n"
625                "  export let x: number;\n"
626                "}\n");
627 }
628 
629 TEST_F(FormatTestJS, NamespacesMayNotWrap) {
630   verifyFormat("declare namespace foobarbaz {\n"
631                "}\n", getGoogleJSStyleWithColumns(18));
632   verifyFormat("declare module foobarbaz {\n"
633                "}\n", getGoogleJSStyleWithColumns(15));
634   verifyFormat("namespace foobarbaz {\n"
635                "}\n", getGoogleJSStyleWithColumns(10));
636   verifyFormat("module foobarbaz {\n"
637                "}\n", getGoogleJSStyleWithColumns(7));
638 }
639 
640 TEST_F(FormatTestJS, AmbientDeclarations) {
641   FormatStyle NineCols = getGoogleJSStyleWithColumns(9);
642   verifyFormat(
643       "declare class\n"
644       "    X {}",
645       NineCols);
646   verifyFormat(
647       "declare function\n"
648       "x();",  // TODO(martinprobst): should ideally be indented.
649       NineCols);
650   verifyFormat("declare function foo();\n"
651                "let x = 1;\n");
652   verifyFormat("declare function foo(): string;\n"
653                "let x = 1;\n");
654   verifyFormat("declare function foo(): {x: number};\n"
655                "let x = 1;\n");
656   verifyFormat("declare class X {}\n"
657                "let x = 1;\n");
658   verifyFormat("declare interface Y {}\n"
659                "let x = 1;\n");
660   verifyFormat(
661       "declare enum X {\n"
662       "}",
663       NineCols);
664   verifyFormat(
665       "declare let\n"
666       "    x: number;",
667       NineCols);
668 }
669 
670 TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
671   verifyFormat("function outer1(a, b) {\n"
672                "  function inner1(a, b) {\n"
673                "    return a;\n"
674                "  }\n"
675                "  inner1(a, b);\n"
676                "}\n"
677                "function outer2(a, b) {\n"
678                "  function inner2(a, b) {\n"
679                "    return a;\n"
680                "  }\n"
681                "  inner2(a, b);\n"
682                "}");
683   verifyFormat("function f() {}");
684   verifyFormat("function aFunction() {}\n"
685                "(function f() {\n"
686                "  var x = 1;\n"
687                "}());\n");
688   verifyFormat("function aFunction() {}\n"
689                "{\n"
690                "  let x = 1;\n"
691                "  console.log(x);\n"
692                "}\n");
693 }
694 
695 TEST_F(FormatTestJS, GeneratorFunctions) {
696   verifyFormat("function* f() {\n"
697                "  let x = 1;\n"
698                "  yield x;\n"
699                "  yield* something();\n"
700                "  yield [1, 2];\n"
701                "  yield {a: 1};\n"
702                "}");
703   verifyFormat("function*\n"
704                "    f() {\n"
705                "}",
706                getGoogleJSStyleWithColumns(8));
707   verifyFormat("export function* f() {\n"
708                "  yield 1;\n"
709                "}\n");
710   verifyFormat("class X {\n"
711                "  * generatorMethod() {\n"
712                "    yield x;\n"
713                "  }\n"
714                "}");
715   verifyFormat("var x = {\n"
716                "  a: function*() {\n"
717                "    //\n"
718                "  }\n"
719                "}\n");
720 }
721 
722 TEST_F(FormatTestJS, AsyncFunctions) {
723   verifyFormat("async function f() {\n"
724                "  let x = 1;\n"
725                "  return fetch(x);\n"
726                "}");
727   verifyFormat("async function f() {\n"
728                "  return 1;\n"
729                "}\n"
730                "\n"
731                "function a() {\n"
732                "  return 1;\n"
733                "}\n",
734                "  async   function f() {\n"
735                "   return 1;\n"
736                "}\n"
737                "\n"
738                "   function a() {\n"
739                "  return   1;\n"
740                "}  \n");
741   verifyFormat("async function* f() {\n"
742                "  yield fetch(x);\n"
743                "}");
744   verifyFormat("export async function f() {\n"
745                "  return fetch(x);\n"
746                "}");
747   verifyFormat("let x = async () => f();");
748   verifyFormat("let x = async function() {\n"
749                "  f();\n"
750                "};");
751   verifyFormat("let x = async();");
752   verifyFormat("class X {\n"
753                "  async asyncMethod() {\n"
754                "    return fetch(1);\n"
755                "  }\n"
756                "}");
757   verifyFormat("function initialize() {\n"
758                "  // Comment.\n"
759                "  return async.then();\n"
760                "}\n");
761   verifyFormat("for await (const x of y) {\n"
762                "  console.log(x);\n"
763                "}\n");
764   verifyFormat("function asyncLoop() {\n"
765                "  for await (const x of y) {\n"
766                "    console.log(x);\n"
767                "  }\n"
768                "}\n");
769 }
770 
771 TEST_F(FormatTestJS, FunctionParametersTrailingComma) {
772   verifyFormat("function trailingComma(\n"
773                "    p1,\n"
774                "    p2,\n"
775                "    p3,\n"
776                ") {\n"
777                "  a;  //\n"
778                "}\n",
779                "function trailingComma(p1, p2, p3,) {\n"
780                "  a;  //\n"
781                "}\n");
782   verifyFormat("trailingComma(\n"
783                "    p1,\n"
784                "    p2,\n"
785                "    p3,\n"
786                ");\n",
787                "trailingComma(p1, p2, p3,);\n");
788   verifyFormat("trailingComma(\n"
789                "    p1  // hello\n"
790                ");\n",
791                "trailingComma(p1 // hello\n"
792                ");\n");
793 }
794 
795 TEST_F(FormatTestJS, ArrayLiterals) {
796   verifyFormat("var aaaaa: List<SomeThing> =\n"
797                "    [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];");
798   verifyFormat("return [\n"
799                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
800                "  ccccccccccccccccccccccccccc\n"
801                "];");
802   verifyFormat("return [\n"
803                "  aaaa().bbbbbbbb('A'),\n"
804                "  aaaa().bbbbbbbb('B'),\n"
805                "  aaaa().bbbbbbbb('C'),\n"
806                "];");
807   verifyFormat("var someVariable = SomeFunction([\n"
808                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
809                "  ccccccccccccccccccccccccccc\n"
810                "]);");
811   verifyFormat("var someVariable = SomeFunction([\n"
812                "  [aaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbb],\n"
813                "]);",
814                getGoogleJSStyleWithColumns(51));
815   verifyFormat("var someVariable = SomeFunction(aaaa, [\n"
816                "  aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
817                "  ccccccccccccccccccccccccccc\n"
818                "]);");
819   verifyFormat("var someVariable = SomeFunction(\n"
820                "    aaaa,\n"
821                "    [\n"
822                "      aaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
823                "      cccccccccccccccccccccccccc\n"
824                "    ],\n"
825                "    aaaa);");
826   verifyFormat("var aaaa = aaaaa ||  // wrap\n"
827                "    [];");
828 
829   verifyFormat("someFunction([], {a: a});");
830 
831   verifyFormat("var string = [\n"
832                "  'aaaaaa',\n"
833                "  'bbbbbb',\n"
834                "].join('+');");
835 }
836 
837 TEST_F(FormatTestJS, ColumnLayoutForArrayLiterals) {
838   verifyFormat("var array = [\n"
839                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
840                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
841                "];");
842   verifyFormat("var array = someFunction([\n"
843                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
844                "  a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
845                "]);");
846 }
847 
848 TEST_F(FormatTestJS, FunctionLiterals) {
849   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
850   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
851   verifyFormat("doFoo(function() {});");
852   verifyFormat("doFoo(function() { return 1; });", Style);
853   verifyFormat("var func = function() {\n"
854                "  return 1;\n"
855                "};");
856   verifyFormat("var func =  //\n"
857                "    function() {\n"
858                "  return 1;\n"
859                "};");
860   verifyFormat("return {\n"
861                "  body: {\n"
862                "    setAttribute: function(key, val) { this[key] = val; },\n"
863                "    getAttribute: function(key) { return this[key]; },\n"
864                "    style: {direction: ''}\n"
865                "  }\n"
866                "};",
867                Style);
868   verifyFormat("abc = xyz ? function() {\n"
869                "  return 1;\n"
870                "} : function() {\n"
871                "  return -1;\n"
872                "};");
873 
874   verifyFormat("var closure = goog.bind(\n"
875                "    function() {  // comment\n"
876                "      foo();\n"
877                "      bar();\n"
878                "    },\n"
879                "    this, arg1IsReallyLongAndNeedsLineBreaks,\n"
880                "    arg3IsReallyLongAndNeedsLineBreaks);");
881   verifyFormat("var closure = goog.bind(function() {  // comment\n"
882                "  foo();\n"
883                "  bar();\n"
884                "}, this);");
885   verifyFormat("return {\n"
886                "  a: 'E',\n"
887                "  b: function() {\n"
888                "    return function() {\n"
889                "      f();  //\n"
890                "    };\n"
891                "  }\n"
892                "};");
893   verifyFormat("{\n"
894                "  var someVariable = function(x) {\n"
895                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
896                "  };\n"
897                "}");
898   verifyFormat("someLooooooooongFunction(\n"
899                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
900                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
901                "    function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
902                "      // code\n"
903                "    });");
904 
905   verifyFormat("return {\n"
906                "  a: function SomeFunction() {\n"
907                "    // ...\n"
908                "    return 1;\n"
909                "  }\n"
910                "};");
911   verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
912                "    .then(goog.bind(function(aaaaaaaaaaa) {\n"
913                "      someFunction();\n"
914                "      someFunction();\n"
915                "    }, this), aaaaaaaaaaaaaaaaa);");
916 
917   verifyFormat("someFunction(goog.bind(function() {\n"
918                "  doSomething();\n"
919                "  doSomething();\n"
920                "}, this), goog.bind(function() {\n"
921                "  doSomething();\n"
922                "  doSomething();\n"
923                "}, this));");
924 
925   verifyFormat("SomeFunction(function() {\n"
926                "  foo();\n"
927                "  bar();\n"
928                "}.bind(this));");
929 
930   verifyFormat("SomeFunction((function() {\n"
931                "               foo();\n"
932                "               bar();\n"
933                "             }).bind(this));");
934 
935   // FIXME: This is bad, we should be wrapping before "function() {".
936   verifyFormat("someFunction(function() {\n"
937                "  doSomething();  // break\n"
938                "})\n"
939                "    .doSomethingElse(\n"
940                "        // break\n"
941                "    );");
942 
943   Style.ColumnLimit = 33;
944   verifyFormat("f({a: function() { return 1; }});", Style);
945   Style.ColumnLimit = 32;
946   verifyFormat("f({\n"
947                "  a: function() { return 1; }\n"
948                "});",
949                Style);
950 
951 }
952 
953 TEST_F(FormatTestJS, DontWrapEmptyLiterals) {
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   verifyFormat("(aaaaaaaaaaaaaaaaaaaaa.getData as jasmine.Spy)\n"
959                "    .and.returnValue(Observable.of(()));");
960 }
961 
962 TEST_F(FormatTestJS, InliningFunctionLiterals) {
963   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
964   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
965   verifyFormat("var func = function() {\n"
966                "  return 1;\n"
967                "};",
968                Style);
969   verifyFormat("var func = doSomething(function() { return 1; });", Style);
970   verifyFormat("var outer = function() {\n"
971                "  var inner = function() { return 1; }\n"
972                "};",
973                Style);
974   verifyFormat("function outer1(a, b) {\n"
975                "  function inner1(a, b) { return a; }\n"
976                "}",
977                Style);
978 
979   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
980   verifyFormat("var func = function() { return 1; };", Style);
981   verifyFormat("var func = doSomething(function() { return 1; });", Style);
982   verifyFormat(
983       "var outer = function() { var inner = function() { return 1; } };",
984       Style);
985   verifyFormat("function outer1(a, b) {\n"
986                "  function inner1(a, b) { return a; }\n"
987                "}",
988                Style);
989 
990   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
991   verifyFormat("var func = function() {\n"
992                "  return 1;\n"
993                "};",
994                Style);
995   verifyFormat("var func = doSomething(function() {\n"
996                "  return 1;\n"
997                "});",
998                Style);
999   verifyFormat("var outer = function() {\n"
1000                "  var inner = function() {\n"
1001                "    return 1;\n"
1002                "  }\n"
1003                "};",
1004                Style);
1005   verifyFormat("function outer1(a, b) {\n"
1006                "  function inner1(a, b) {\n"
1007                "    return a;\n"
1008                "  }\n"
1009                "}",
1010                Style);
1011 
1012   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1013   verifyFormat("var func = function() {\n"
1014                "  return 1;\n"
1015                "};",
1016                Style);
1017 }
1018 
1019 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
1020   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
1021   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1022   verifyFormat("promise.then(\n"
1023                "    function success() {\n"
1024                "      doFoo();\n"
1025                "      doBar();\n"
1026                "    },\n"
1027                "    function error() {\n"
1028                "      doFoo();\n"
1029                "      doBaz();\n"
1030                "    },\n"
1031                "    []);\n");
1032   verifyFormat("promise.then(\n"
1033                "    function success() {\n"
1034                "      doFoo();\n"
1035                "      doBar();\n"
1036                "    },\n"
1037                "    [],\n"
1038                "    function error() {\n"
1039                "      doFoo();\n"
1040                "      doBaz();\n"
1041                "    });\n");
1042   verifyFormat("promise.then(\n"
1043                "    [],\n"
1044                "    function success() {\n"
1045                "      doFoo();\n"
1046                "      doBar();\n"
1047                "    },\n"
1048                "    function error() {\n"
1049                "      doFoo();\n"
1050                "      doBaz();\n"
1051                "    });\n");
1052 
1053   verifyFormat("getSomeLongPromise()\n"
1054                "    .then(function(value) { body(); })\n"
1055                "    .thenCatch(function(error) {\n"
1056                "      body();\n"
1057                "      body();\n"
1058                "    });",
1059                Style);
1060   verifyFormat("getSomeLongPromise()\n"
1061                "    .then(function(value) {\n"
1062                "      body();\n"
1063                "      body();\n"
1064                "    })\n"
1065                "    .thenCatch(function(error) {\n"
1066                "      body();\n"
1067                "      body();\n"
1068                "    });");
1069 
1070   verifyFormat("getSomeLongPromise()\n"
1071                "    .then(function(value) { body(); })\n"
1072                "    .thenCatch(function(error) { body(); });",
1073                Style);
1074 
1075   verifyFormat("return [aaaaaaaaaaaaaaaaaaaaaa]\n"
1076                "    .aaaaaaa(function() {\n"
1077                "      //\n"
1078                "    })\n"
1079                "    .bbbbbb();");
1080 }
1081 
1082 TEST_F(FormatTestJS, ArrowFunctions) {
1083   verifyFormat("var x = (a) => {\n"
1084                "  return a;\n"
1085                "};");
1086   verifyFormat("var x = (a) => {\n"
1087                "  function y() {\n"
1088                "    return 42;\n"
1089                "  }\n"
1090                "  return a;\n"
1091                "};");
1092   verifyFormat("var x = (a: type): {some: type} => {\n"
1093                "  return a;\n"
1094                "};");
1095   verifyFormat("var x = (a) => a;");
1096   verifyFormat("return () => [];");
1097   verifyFormat("var aaaaaaaaaaaaaaaaaaaa = {\n"
1098                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
1099                "      (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1100                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) =>\n"
1101                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1102                "};");
1103   verifyFormat("var a = a.aaaaaaa(\n"
1104                "    (a: a) => aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) &&\n"
1105                "        aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
1106   verifyFormat("var a = a.aaaaaaa(\n"
1107                "    (a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) ?\n"
1108                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb) :\n"
1109                "        aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));");
1110 
1111   // FIXME: This is bad, we should be wrapping before "() => {".
1112   verifyFormat("someFunction(() => {\n"
1113                "  doSomething();  // break\n"
1114                "})\n"
1115                "    .doSomethingElse(\n"
1116                "        // break\n"
1117                "    );");
1118   verifyFormat("const f = (x: string|null): string|null => {\n"
1119                "  return x;\n"
1120                "}\n");
1121 }
1122 
1123 TEST_F(FormatTestJS, ReturnStatements) {
1124   verifyFormat("function() {\n"
1125                "  return [hello, world];\n"
1126                "}");
1127 }
1128 
1129 TEST_F(FormatTestJS, ForLoops) {
1130   verifyFormat("for (var i in [2, 3]) {\n"
1131                "}");
1132   verifyFormat("for (var i of [2, 3]) {\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] of [x]) {\n"
1139                "}");
1140   verifyFormat("for (let {a, b} in x) {\n"
1141                "}");
1142 }
1143 
1144 TEST_F(FormatTestJS, WrapRespectsAutomaticSemicolonInsertion) {
1145   // The following statements must not wrap, as otherwise the program meaning
1146   // would change due to automatic semicolon insertion.
1147   // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
1148   verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10));
1149   verifyFormat("yield aaaaa;", getGoogleJSStyleWithColumns(10));
1150   verifyFormat("return /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10));
1151   verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10));
1152   verifyFormat("continue /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10));
1153   verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10));
1154   verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
1155   verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
1156   verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
1157   verifyFormat("return [\n"
1158                "  aaa\n"
1159                "];",
1160                getGoogleJSStyleWithColumns(12));
1161   verifyFormat("class X {\n"
1162                "  readonly ratherLongField =\n"
1163                "      1;\n"
1164                "}",
1165                "class X {\n"
1166                "  readonly ratherLongField = 1;\n"
1167                "}",
1168                getGoogleJSStyleWithColumns(20));
1169   verifyFormat("const x = (5 + 9)\n"
1170                "const y = 3\n",
1171                "const x = (   5 +    9)\n"
1172                "const y = 3\n");
1173   // Ideally the foo() bit should be indented relative to the async function().
1174   verifyFormat("async function\n"
1175                "foo() {}",
1176                getGoogleJSStyleWithColumns(10));
1177   verifyFormat("await theReckoning;", getGoogleJSStyleWithColumns(10));
1178   verifyFormat("some['a']['b']", getGoogleJSStyleWithColumns(10));
1179   verifyFormat("x = (a['a']\n"
1180                "      ['b']);",
1181                getGoogleJSStyleWithColumns(10));
1182   verifyFormat("function f() {\n"
1183                "  return foo.bar(\n"
1184                "      (param): param is {\n"
1185                "        a: SomeType\n"
1186                "      }&ABC => 1)\n"
1187                "}",
1188                getGoogleJSStyleWithColumns(25));
1189 }
1190 
1191 TEST_F(FormatTestJS, AddsIsTheDictKeyOnNewline) {
1192   // Do not confuse is, the dict key with is, the type matcher. Put is, the dict
1193   // key, on a newline.
1194   verifyFormat("Polymer({\n"
1195                "  is: '',  //\n"
1196                "  rest: 1\n"
1197                "});",
1198                getGoogleJSStyleWithColumns(20));
1199 }
1200 
1201 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
1202   verifyFormat("a\n"
1203                "b;",
1204                " a \n"
1205                " b ;");
1206   verifyFormat("a()\n"
1207                "b;",
1208                " a ()\n"
1209                " b ;");
1210   verifyFormat("a[b]\n"
1211                "c;",
1212                "a [b]\n"
1213                "c ;");
1214   verifyFormat("1\n"
1215                "a;",
1216                "1 \n"
1217                "a ;");
1218   verifyFormat("a\n"
1219                "1;",
1220                "a \n"
1221                "1 ;");
1222   verifyFormat("a\n"
1223                "'x';",
1224                "a \n"
1225                " 'x';");
1226   verifyFormat("a++\n"
1227                "b;",
1228                "a ++\n"
1229                "b ;");
1230   verifyFormat("a\n"
1231                "!b && c;",
1232                "a \n"
1233                " ! b && c;");
1234   verifyFormat("a\n"
1235                "if (1) f();",
1236                " a\n"
1237                " if (1) f();");
1238   verifyFormat("a\n"
1239                "class X {}",
1240                " a\n"
1241                " class X {}");
1242   verifyFormat("var a", "var\n"
1243                         "a");
1244   verifyFormat("x instanceof String", "x\n"
1245                                       "instanceof\n"
1246                                       "String");
1247   verifyFormat("function f(@Foo bar) {}", "function f(@Foo\n"
1248                                           "  bar) {}");
1249   verifyFormat("function f(@Foo(Param) bar) {}", "function f(@Foo(Param)\n"
1250                                                  "  bar) {}");
1251   verifyFormat("a = true\n"
1252                "return 1",
1253                "a = true\n"
1254                "  return   1");
1255   verifyFormat("a = 's'\n"
1256                "return 1",
1257                "a = 's'\n"
1258                "  return   1");
1259   verifyFormat("a = null\n"
1260                "return 1",
1261                "a = null\n"
1262                "  return   1");
1263   // Below "class Y {}" should ideally be on its own line.
1264   verifyFormat(
1265       "x = {\n"
1266       "  a: 1\n"
1267       "} class Y {}",
1268       "  x  =  {a  : 1}\n"
1269       "   class  Y {  }");
1270   verifyFormat(
1271       "if (x) {\n"
1272       "}\n"
1273       "return 1",
1274       "if (x) {}\n"
1275       " return   1");
1276   verifyFormat(
1277       "if (x) {\n"
1278       "}\n"
1279       "class X {}",
1280       "if (x) {}\n"
1281       " class X {}");
1282 }
1283 
1284 TEST_F(FormatTestJS, ImportExportASI) {
1285   verifyFormat(
1286       "import {x} from 'y'\n"
1287       "export function z() {}",
1288       "import   {x} from 'y'\n"
1289       "  export function z() {}");
1290   // Below "class Y {}" should ideally be on its own line.
1291   verifyFormat(
1292       "export {x} class Y {}",
1293       "  export {x}\n"
1294       "  class  Y {\n}");
1295   verifyFormat(
1296       "if (x) {\n"
1297       "}\n"
1298       "export class Y {}",
1299       "if ( x ) { }\n"
1300       " export class Y {}");
1301 }
1302 
1303 TEST_F(FormatTestJS, ClosureStyleCasts) {
1304   verifyFormat("var x = /** @type {foo} */ (bar);");
1305 }
1306 
1307 TEST_F(FormatTestJS, TryCatch) {
1308   verifyFormat("try {\n"
1309                "  f();\n"
1310                "} catch (e) {\n"
1311                "  g();\n"
1312                "} finally {\n"
1313                "  h();\n"
1314                "}");
1315 
1316   // But, of course, "catch" is a perfectly fine function name in JavaScript.
1317   verifyFormat("someObject.catch();");
1318   verifyFormat("someObject.new();");
1319 }
1320 
1321 TEST_F(FormatTestJS, StringLiteralConcatenation) {
1322   verifyFormat("var literal = 'hello ' +\n"
1323                "    'world';");
1324 }
1325 
1326 TEST_F(FormatTestJS, RegexLiteralClassification) {
1327   // Regex literals.
1328   verifyFormat("var regex = /abc/;");
1329   verifyFormat("f(/abc/);");
1330   verifyFormat("f(abc, /abc/);");
1331   verifyFormat("some_map[/abc/];");
1332   verifyFormat("var x = a ? /abc/ : /abc/;");
1333   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
1334   verifyFormat("var x = !/abc/.test(y);");
1335   verifyFormat("var x = foo()! / 10;");
1336   verifyFormat("var x = a && /abc/.test(y);");
1337   verifyFormat("var x = a || /abc/.test(y);");
1338   verifyFormat("var x = a + /abc/.search(y);");
1339   verifyFormat("/abc/.search(y);");
1340   verifyFormat("var regexs = {/abc/, /abc/};");
1341   verifyFormat("return /abc/;");
1342 
1343   // Not regex literals.
1344   verifyFormat("var a = a / 2 + b / 3;");
1345   verifyFormat("var a = a++ / 2;");
1346   // Prefix unary can operate on regex literals, not that it makes sense.
1347   verifyFormat("var a = ++/a/;");
1348 
1349   // This is a known issue, regular expressions are incorrectly detected if
1350   // directly following a closing parenthesis.
1351   verifyFormat("if (foo) / bar /.exec(baz);");
1352 }
1353 
1354 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
1355   verifyFormat("var regex = /=/;");
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 = /^a$/;");
1362   verifyFormat("var regex = /\\/a/;");
1363   verifyFormat("var regex = /(?:x)/;");
1364   verifyFormat("var regex = /x(?=y)/;");
1365   verifyFormat("var regex = /x(?!y)/;");
1366   verifyFormat("var regex = /x|y/;");
1367   verifyFormat("var regex = /a{2}/;");
1368   verifyFormat("var regex = /a{1,3}/;");
1369 
1370   verifyFormat("var regex = /[abc]/;");
1371   verifyFormat("var regex = /[^abc]/;");
1372   verifyFormat("var regex = /[\\b]/;");
1373   verifyFormat("var regex = /[/]/;");
1374   verifyFormat("var regex = /[\\/]/;");
1375   verifyFormat("var regex = /\\[/;");
1376   verifyFormat("var regex = /\\\\[/]/;");
1377   verifyFormat("var regex = /}[\"]/;");
1378   verifyFormat("var regex = /}[/\"]/;");
1379   verifyFormat("var regex = /}[\"/]/;");
1380 
1381   verifyFormat("var regex = /\\b/;");
1382   verifyFormat("var regex = /\\B/;");
1383   verifyFormat("var regex = /\\d/;");
1384   verifyFormat("var regex = /\\D/;");
1385   verifyFormat("var regex = /\\f/;");
1386   verifyFormat("var regex = /\\n/;");
1387   verifyFormat("var regex = /\\r/;");
1388   verifyFormat("var regex = /\\s/;");
1389   verifyFormat("var regex = /\\S/;");
1390   verifyFormat("var regex = /\\t/;");
1391   verifyFormat("var regex = /\\v/;");
1392   verifyFormat("var regex = /\\w/;");
1393   verifyFormat("var regex = /\\W/;");
1394   verifyFormat("var regex = /a(a)\\1/;");
1395   verifyFormat("var regex = /\\0/;");
1396   verifyFormat("var regex = /\\\\/g;");
1397   verifyFormat("var regex = /\\a\\\\/g;");
1398   verifyFormat("var regex = /\a\\//g;");
1399   verifyFormat("var regex = /a\\//;\n"
1400                "var x = 0;");
1401   verifyFormat("var regex = /'/g;", "var regex = /'/g ;");
1402   verifyFormat("var regex = /'/g;  //'", "var regex = /'/g ; //'");
1403   verifyFormat("var regex = /\\/*/;\n"
1404                "var x = 0;",
1405                "var regex = /\\/*/;\n"
1406                "var x=0;");
1407   verifyFormat("var x = /a\\//;", "var x = /a\\//  \n;");
1408   verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
1409   verifyFormat("var regex =\n"
1410                "    /\"/;",
1411                getGoogleJSStyleWithColumns(15));
1412   verifyFormat("var regex =  //\n"
1413                "    /a/;");
1414   verifyFormat("var regexs = [\n"
1415                "  /d/,   //\n"
1416                "  /aa/,  //\n"
1417                "];");
1418 }
1419 
1420 TEST_F(FormatTestJS, RegexLiteralModifiers) {
1421   verifyFormat("var regex = /abc/g;");
1422   verifyFormat("var regex = /abc/i;");
1423   verifyFormat("var regex = /abc/m;");
1424   verifyFormat("var regex = /abc/y;");
1425 }
1426 
1427 TEST_F(FormatTestJS, RegexLiteralLength) {
1428   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1429                getGoogleJSStyleWithColumns(60));
1430   verifyFormat("var regex =\n"
1431                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1432                getGoogleJSStyleWithColumns(60));
1433   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
1434                getGoogleJSStyleWithColumns(50));
1435 }
1436 
1437 TEST_F(FormatTestJS, RegexLiteralExamples) {
1438   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
1439 }
1440 
1441 TEST_F(FormatTestJS, IgnoresMpegTS) {
1442   std::string MpegTS(200, ' ');
1443   MpegTS.replace(0, strlen("nearlyLooks  +   like +   ts + code;  "),
1444                  "nearlyLooks  +   like +   ts + code;  ");
1445   MpegTS[0] = 0x47;
1446   MpegTS[188] = 0x47;
1447   verifyFormat(MpegTS, MpegTS);
1448 }
1449 
1450 TEST_F(FormatTestJS, TypeAnnotations) {
1451   verifyFormat("var x: string;");
1452   verifyFormat("var x: {a: string; b: number;} = {};");
1453   verifyFormat("function x(): string {\n  return 'x';\n}");
1454   verifyFormat("function x(): {x: string} {\n  return {x: 'x'};\n}");
1455   verifyFormat("function x(y: string): string {\n  return 'x';\n}");
1456   verifyFormat("for (var y: string in x) {\n  x();\n}");
1457   verifyFormat("for (var y: string of x) {\n  x();\n}");
1458   verifyFormat("function x(y: {a?: number;} = {}): number {\n"
1459                "  return 12;\n"
1460                "}");
1461   verifyFormat("const x: Array<{a: number; b: string;}> = [];");
1462   verifyFormat("((a: string, b: number): string => a + b);");
1463   verifyFormat("var x: (y: number) => string;");
1464   verifyFormat("var x: P<string, (a: number) => string>;");
1465   verifyFormat("var x = {\n"
1466                "  y: function(): z {\n"
1467                "    return 1;\n"
1468                "  }\n"
1469                "};");
1470   verifyFormat("var x = {\n"
1471                "  y: function(): {a: number} {\n"
1472                "    return 1;\n"
1473                "  }\n"
1474                "};");
1475   verifyFormat("function someFunc(args: string[]):\n"
1476                "    {longReturnValue: string[]} {}",
1477                getGoogleJSStyleWithColumns(60));
1478   verifyFormat(
1479       "var someValue = (v as aaaaaaaaaaaaaaaaaaaa<T>[])\n"
1480       "                    .someFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1481   verifyFormat("const xIsALongIdent:\n""    YJustBarelyFitsLinex[];",
1482       getGoogleJSStyleWithColumns(20));
1483 }
1484 
1485 TEST_F(FormatTestJS, UnionIntersectionTypes) {
1486   verifyFormat("let x: A|B = A | B;");
1487   verifyFormat("let x: A&B|C = A & B;");
1488   verifyFormat("let x: Foo<A|B> = new Foo<A|B>();");
1489   verifyFormat("function(x: A|B): C&D {}");
1490   verifyFormat("function(x: A|B = A | B): C&D {}");
1491   verifyFormat("function x(path: number|string) {}");
1492   verifyFormat("function x(): string|number {}");
1493   verifyFormat("type Foo = Bar|Baz;");
1494   verifyFormat("type Foo = Bar<X>|Baz;");
1495   verifyFormat("type Foo = (Bar<X>|Baz);");
1496   verifyFormat("let x: Bar|Baz;");
1497   verifyFormat("let x: Bar<X>|Baz;");
1498   verifyFormat("let x: (Foo|Bar)[];");
1499   verifyFormat("type X = {\n"
1500                "  a: Foo|Bar;\n"
1501                "};");
1502   verifyFormat("export type X = {\n"
1503                "  a: Foo|Bar;\n"
1504                "};");
1505 }
1506 
1507 TEST_F(FormatTestJS, UnionIntersectionTypesInObjectType) {
1508   verifyFormat("let x: {x: number|null} = {x: number | null};");
1509   verifyFormat("let nested: {x: {y: number|null}};");
1510   verifyFormat("let mixed: {x: [number|null, {w: number}]};");
1511   verifyFormat("class X {\n"
1512                "  contructor(x: {\n"
1513                "    a: a|null,\n"
1514                "    b: b|null,\n"
1515                "  }) {}\n"
1516                "}");
1517 }
1518 
1519 TEST_F(FormatTestJS, ClassDeclarations) {
1520   verifyFormat("class C {\n  x: string = 12;\n}");
1521   verifyFormat("class C {\n  x(): string => 12;\n}");
1522   verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
1523   verifyFormat("class C {\n"
1524                "  foo() {}\n"
1525                "  [bar]() {}\n"
1526                "}\n");
1527   verifyFormat("class C {\n  private x: string = 12;\n}");
1528   verifyFormat("class C {\n  private static x: string = 12;\n}");
1529   verifyFormat("class C {\n  static x(): string {\n    return 'asd';\n  }\n}");
1530   verifyFormat("class C extends P implements I {}");
1531   verifyFormat("class C extends p.P implements i.I {}");
1532   verifyFormat(
1533       "x(class {\n"
1534       "  a(): A {}\n"
1535       "});");
1536   verifyFormat("class Test {\n"
1537                "  aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
1538                "      aaaaaaaaaaaaaaaaaaaaaa {}\n"
1539                "}");
1540   verifyFormat("foo = class Name {\n"
1541                "  constructor() {}\n"
1542                "};");
1543   verifyFormat("foo = class {\n"
1544                "  constructor() {}\n"
1545                "};");
1546   verifyFormat("class C {\n"
1547                "  x: {y: Z;} = {};\n"
1548                "  private y: {y: Z;} = {};\n"
1549                "}");
1550 
1551   // ':' is not a type declaration here.
1552   verifyFormat("class X {\n"
1553                "  subs = {\n"
1554                "    'b': {\n"
1555                "      'c': 1,\n"
1556                "    },\n"
1557                "  };\n"
1558                "}");
1559   verifyFormat("@Component({\n"
1560                "  moduleId: module.id,\n"
1561                "})\n"
1562                "class SessionListComponent implements OnDestroy, OnInit {\n"
1563                "}");
1564 }
1565 
1566 TEST_F(FormatTestJS, StrictPropInitWrap) {
1567   const FormatStyle &Style = getGoogleJSStyleWithColumns(22);
1568   verifyFormat("class X {\n"
1569                "  strictPropInitField!:\n"
1570                "      string;\n"
1571                "}",
1572                Style);
1573 }
1574 
1575 TEST_F(FormatTestJS, InterfaceDeclarations) {
1576   verifyFormat("interface I {\n"
1577                "  x: string;\n"
1578                "  enum: string[];\n"
1579                "  enum?: string[];\n"
1580                "}\n"
1581                "var y;");
1582   // Ensure that state is reset after parsing the interface.
1583   verifyFormat("interface a {}\n"
1584                "export function b() {}\n"
1585                "var x;");
1586 
1587   // Arrays of object type literals.
1588   verifyFormat("interface I {\n"
1589                "  o: {}[];\n"
1590                "}");
1591 }
1592 
1593 TEST_F(FormatTestJS, ObjectTypesInExtendsImplements) {
1594   verifyFormat("class C extends {} {}");
1595   verifyFormat("class C implements {bar: number} {}");
1596   // Somewhat odd, but probably closest to reasonable formatting?
1597   verifyFormat("class C implements {\n"
1598                "  bar: number,\n"
1599                "  baz: string,\n"
1600                "} {}");
1601   verifyFormat("class C<P extends {}> {}");
1602 }
1603 
1604 TEST_F(FormatTestJS, EnumDeclarations) {
1605   verifyFormat("enum Foo {\n"
1606                "  A = 1,\n"
1607                "  B\n"
1608                "}");
1609   verifyFormat("export /* somecomment*/ enum Foo {\n"
1610                "  A = 1,\n"
1611                "  B\n"
1612                "}");
1613   verifyFormat("enum Foo {\n"
1614                "  A = 1,  // comment\n"
1615                "  B\n"
1616                "}\n"
1617                "var x = 1;");
1618   verifyFormat("const enum Foo {\n"
1619                "  A = 1,\n"
1620                "  B\n"
1621                "}");
1622   verifyFormat("export const enum Foo {\n"
1623                "  A = 1,\n"
1624                "  B\n"
1625                "}");
1626 }
1627 
1628 TEST_F(FormatTestJS, Decorators) {
1629   verifyFormat("@A\nclass C {\n}");
1630   verifyFormat("@A({arg: 'value'})\nclass C {\n}");
1631   verifyFormat("@A\n@B\nclass C {\n}");
1632   verifyFormat("class C {\n  @A x: string;\n}");
1633   verifyFormat("class C {\n"
1634                "  @A\n"
1635                "  private x(): string {\n"
1636                "    return 'y';\n"
1637                "  }\n"
1638                "}");
1639   verifyFormat("class C {\n"
1640                "  private x(@A x: string) {}\n"
1641                "}");
1642   verifyFormat("class X {}\n"
1643                "class Y {}");
1644   verifyFormat("class X {\n"
1645                "  @property() private isReply = false;\n"
1646                "}\n");
1647 }
1648 
1649 TEST_F(FormatTestJS, TypeAliases) {
1650   verifyFormat("type X = number;\n"
1651                "class C {}");
1652   verifyFormat("type X<Y> = Z<Y>;");
1653   verifyFormat("type X = {\n"
1654                "  y: number\n"
1655                "};\n"
1656                "class C {}");
1657   verifyFormat("export type X = {\n"
1658                "  a: string,\n"
1659                "  b?: string,\n"
1660                "};\n");
1661 }
1662 
1663 TEST_F(FormatTestJS, TypeInterfaceLineWrapping) {
1664   const FormatStyle &Style = getGoogleJSStyleWithColumns(20);
1665   verifyFormat("type LongTypeIsReallyUnreasonablyLong =\n"
1666                "    string;\n",
1667                "type LongTypeIsReallyUnreasonablyLong = string;\n",
1668                Style);
1669   verifyFormat(
1670       "interface AbstractStrategyFactoryProvider {\n"
1671       "  a: number\n"
1672       "}\n",
1673       "interface AbstractStrategyFactoryProvider { a: number }\n",
1674       Style);
1675 }
1676 
1677 TEST_F(FormatTestJS, RemoveEmptyLinesInArrowFunctions) {
1678   verifyFormat("x = () => {\n"
1679                "  foo();\n"
1680                "};\n",
1681                "x = () => {\n"
1682                "\n"
1683                "  foo();\n"
1684                "\n"
1685                "};\n");
1686 }
1687 
1688 TEST_F(FormatTestJS, Modules) {
1689   verifyFormat("import SomeThing from 'some/module.js';");
1690   verifyFormat("import {X, Y} from 'some/module.js';");
1691   verifyFormat("import a, {X, Y} from 'some/module.js';");
1692   verifyFormat("import {X, Y,} from 'some/module.js';");
1693   verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
1694   // Ensure Automatic Semicolon Insertion does not break on "as\n".
1695   verifyFormat("import {X as myX} from 'm';", "import {X as\n"
1696                                               " myX} from 'm';");
1697   verifyFormat("import * as lib from 'some/module.js';");
1698   verifyFormat("var x = {import: 1};\nx.import = 2;");
1699 
1700   verifyFormat("export function fn() {\n"
1701                "  return 'fn';\n"
1702                "}");
1703   verifyFormat("export function A() {}\n"
1704                "export default function B() {}\n"
1705                "export function C() {}");
1706   verifyFormat("export default () => {\n"
1707                "  let x = 1;\n"
1708                "  return x;\n"
1709                "}");
1710   verifyFormat("export const x = 12;");
1711   verifyFormat("export default class X {}");
1712   verifyFormat("export {X, Y} from 'some/module.js';");
1713   verifyFormat("export {X, Y,} from 'some/module.js';");
1714   verifyFormat("export {SomeVeryLongExport as X, "
1715                "SomeOtherVeryLongExport as Y} from 'some/module.js';");
1716   // export without 'from' is wrapped.
1717   verifyFormat("export let someRatherLongVariableName =\n"
1718                "    someSurprisinglyLongVariable + someOtherRatherLongVar;");
1719   // ... but not if from is just an identifier.
1720   verifyFormat("export {\n"
1721                "  from as from,\n"
1722                "  someSurprisinglyLongVariable as\n"
1723                "      from\n"
1724                "};",
1725                getGoogleJSStyleWithColumns(20));
1726   verifyFormat("export class C {\n"
1727                "  x: number;\n"
1728                "  y: string;\n"
1729                "}");
1730   verifyFormat("export class X {\n"
1731                "  y: number;\n"
1732                "}");
1733   verifyFormat("export abstract class X {\n"
1734                "  y: number;\n"
1735                "}");
1736   verifyFormat("export default class X {\n"
1737                "  y: number\n"
1738                "}");
1739   verifyFormat("export default function() {\n  return 1;\n}");
1740   verifyFormat("export var x = 12;");
1741   verifyFormat("class C {}\n"
1742                "export function f() {}\n"
1743                "var v;");
1744   verifyFormat("export var x: number = 12;");
1745   verifyFormat("export const y = {\n"
1746                "  a: 1,\n"
1747                "  b: 2\n"
1748                "};");
1749   verifyFormat("export enum Foo {\n"
1750                "  BAR,\n"
1751                "  // adsdasd\n"
1752                "  BAZ\n"
1753                "}");
1754   verifyFormat("export default [\n"
1755                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1756                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
1757                "];");
1758   verifyFormat("export default [];");
1759   verifyFormat("export default () => {};");
1760   verifyFormat("export interface Foo {\n"
1761                "  foo: number;\n"
1762                "}\n"
1763                "export class Bar {\n"
1764                "  blah(): string {\n"
1765                "    return this.blah;\n"
1766                "  };\n"
1767                "}");
1768 }
1769 
1770 TEST_F(FormatTestJS, ImportWrapping) {
1771   verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
1772                " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
1773                "} from 'some/module.js';");
1774   FormatStyle Style = getGoogleJSStyleWithColumns(80);
1775   Style.JavaScriptWrapImports = true;
1776   verifyFormat("import {\n"
1777                "  VeryLongImportsAreAnnoying,\n"
1778                "  VeryLongImportsAreAnnoying,\n"
1779                "  VeryLongImportsAreAnnoying,\n"
1780                "} from 'some/module.js';",
1781                Style);
1782   verifyFormat("import {\n"
1783                "  A,\n"
1784                "  A,\n"
1785                "} from 'some/module.js';",
1786                Style);
1787   verifyFormat("export {\n"
1788                "  A,\n"
1789                "  A,\n"
1790                "} from 'some/module.js';",
1791                Style);
1792   Style.ColumnLimit = 40;
1793   // Using this version of verifyFormat because test::messUp hides the issue.
1794   verifyFormat("import {\n"
1795                "  A,\n"
1796                "} from\n"
1797                "    'some/path/longer/than/column/limit/module.js';",
1798                " import  {  \n"
1799                "    A,  \n"
1800                "  }    from\n"
1801                "      'some/path/longer/than/column/limit/module.js'  ; ",
1802                Style);
1803 }
1804 
1805 TEST_F(FormatTestJS, TemplateStrings) {
1806   // Keeps any whitespace/indentation within the template string.
1807   verifyFormat("var x = `hello\n"
1808             "     ${name}\n"
1809             "  !`;",
1810             "var x    =    `hello\n"
1811                    "     ${  name    }\n"
1812                    "  !`;");
1813 
1814   verifyFormat("var x =\n"
1815                "    `hello ${world}` >= some();",
1816                getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
1817   verifyFormat("var x = `hello ${world}` >= some();",
1818                getGoogleJSStyleWithColumns(35)); // Barely fits.
1819   verifyFormat("var x = `hellö ${wörld}` >= söme();",
1820                getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8.
1821   verifyFormat("var x = `hello\n"
1822             "  ${world}` >=\n"
1823             "    some();",
1824             "var x =\n"
1825                    "    `hello\n"
1826                    "  ${world}` >= some();",
1827                    getGoogleJSStyleWithColumns(21)); // Barely doesn't fit.
1828   verifyFormat("var x = `hello\n"
1829             "  ${world}` >= some();",
1830             "var x =\n"
1831                    "    `hello\n"
1832                    "  ${world}` >= some();",
1833                    getGoogleJSStyleWithColumns(22)); // Barely fits.
1834 
1835   verifyFormat("var x =\n"
1836                "    `h`;",
1837                getGoogleJSStyleWithColumns(11));
1838   verifyFormat("var x =\n    `multi\n  line`;", "var x = `multi\n  line`;",
1839                getGoogleJSStyleWithColumns(13));
1840   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1841                "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
1842   // Repro for an obscure width-miscounting issue with template strings.
1843   verifyFormat(
1844       "someLongVariable =\n"
1845       "    "
1846       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;",
1847       "someLongVariable = "
1848       "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;");
1849 
1850   // Make sure template strings get a proper ColumnWidth assigned, even if they
1851   // are first token in line.
1852   verifyFormat(
1853       "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1854       "    `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
1855 
1856   // Two template strings.
1857   verifyFormat("var x = `hello` == `hello`;");
1858 
1859   // Comments in template strings.
1860   verifyFormat("var x = `//a`;\n"
1861             "var y;",
1862             "var x =\n `//a`;\n"
1863                    "var y  ;");
1864   verifyFormat("var x = `/*a`;\n"
1865                "var y;",
1866                "var x =\n `/*a`;\n"
1867                "var y;");
1868   // Unterminated string literals in a template string.
1869   verifyFormat("var x = `'`;  // comment with matching quote '\n"
1870                "var y;");
1871   verifyFormat("var x = `\"`;  // comment with matching quote \"\n"
1872                "var y;");
1873   verifyFormat("it(`'aaaaaaaaaaaaaaa   `, aaaaaaaaa);",
1874                "it(`'aaaaaaaaaaaaaaa   `,   aaaaaaaaa) ;",
1875                getGoogleJSStyleWithColumns(40));
1876   // Backticks in a comment - not a template string.
1877   verifyFormat("var x = 1  // `/*a`;\n"
1878                "    ;",
1879                "var x =\n 1  // `/*a`;\n"
1880                "    ;");
1881   verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */");
1882   // Comment spans multiple template strings.
1883   verifyFormat("var x = `/*a`;\n"
1884                "var y = ` */ `;",
1885                "var x =\n `/*a`;\n"
1886                "var y =\n ` */ `;");
1887   // Escaped backtick.
1888   verifyFormat("var x = ` \\` a`;\n"
1889                "var y;",
1890                "var x = ` \\` a`;\n"
1891                "var y;");
1892   // Escaped dollar.
1893   verifyFormat("var x = ` \\${foo}`;\n");
1894 
1895   // The token stream can contain two string_literals in sequence, but that
1896   // doesn't mean that they are implicitly concatenated in JavaScript.
1897   verifyFormat("var f = `aaaa ${a ? 'a' : 'b'}`;");
1898 
1899   // Ensure that scopes are appropriately set around evaluated expressions in
1900   // template strings.
1901   verifyFormat("var f = `aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa\n"
1902                "         aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`;",
1903                "var f = `aaaaaaaaaaaaa:${aaaaaaa.  aaaaa} aaaaaaaa\n"
1904                "         aaaaaaaaaaaaa:${  aaaaaaa. aaaaa} aaaaaaaa`;");
1905   verifyFormat("var x = someFunction(`${})`)  //\n"
1906                "            .oooooooooooooooooon();");
1907   verifyFormat("var x = someFunction(`${aaaa}${\n"
1908                "    aaaaa(  //\n"
1909                "        aaaaa)})`);");
1910 }
1911 
1912 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) {
1913   verifyFormat("var f = `aaaaaaaaaaaaaaaaaa: ${\n"
1914                "    aaaaa +  //\n"
1915                "    bbbb}`;",
1916                "var f = `aaaaaaaaaaaaaaaaaa: ${aaaaa +  //\n"
1917                "                               bbbb}`;");
1918   verifyFormat("var f = `\n"
1919                "  aaaaaaaaaaaaaaaaaa: ${\n"
1920                "    aaaaa +  //\n"
1921                "    bbbb}`;",
1922                "var f  =  `\n"
1923                "  aaaaaaaaaaaaaaaaaa: ${   aaaaa  +  //\n"
1924                "                        bbbb }`;");
1925   verifyFormat("var f = `\n"
1926                "  aaaaaaaaaaaaaaaaaa: ${\n"
1927                "    someFunction(\n"
1928                "        aaaaa +  //\n"
1929                "        bbbb)}`;",
1930                "var f  =  `\n"
1931                "  aaaaaaaaaaaaaaaaaa: ${someFunction (\n"
1932                "                            aaaaa  +   //\n"
1933                "                            bbbb)}`;");
1934 
1935   // It might be preferable to wrap before "someFunction".
1936   verifyFormat("var f = `\n"
1937                "  aaaaaaaaaaaaaaaaaa: ${someFunction({\n"
1938                "  aaaa: aaaaa,\n"
1939                "  bbbb: bbbbb,\n"
1940                "})}`;",
1941                "var f  =  `\n"
1942                "  aaaaaaaaaaaaaaaaaa: ${someFunction ({\n"
1943                "                          aaaa:  aaaaa,\n"
1944                "                          bbbb:  bbbbb,\n"
1945                "                        })}`;");
1946 }
1947 
1948 TEST_F(FormatTestJS, TemplateStringASI) {
1949   verifyFormat("var x = `hello${world}`;", "var x = `hello${\n"
1950                                            "    world\n"
1951                                            "}`;");
1952 }
1953 
1954 TEST_F(FormatTestJS, NestedTemplateStrings) {
1955   verifyFormat(
1956       "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;");
1957   verifyFormat("var x = `he${({text: 'll'}.text)}o`;");
1958 
1959   // Crashed at some point.
1960   verifyFormat("}");
1961 }
1962 
1963 TEST_F(FormatTestJS, TaggedTemplateStrings) {
1964   verifyFormat("var x = html`<ul>`;");
1965   verifyFormat("yield `hello`;");
1966 }
1967 
1968 TEST_F(FormatTestJS, CastSyntax) {
1969   verifyFormat("var x = <type>foo;");
1970   verifyFormat("var x = foo as type;");
1971   verifyFormat("let x = (a + b) as\n"
1972                "    LongTypeIsLong;",
1973                getGoogleJSStyleWithColumns(20));
1974   verifyFormat("foo = <Bar[]>[\n"
1975                "  1,  //\n"
1976                "  2\n"
1977                "];");
1978   verifyFormat("var x = [{x: 1} as type];");
1979   verifyFormat("x = x as [a, b];");
1980   verifyFormat("x = x as {a: string};");
1981   verifyFormat("x = x as (string);");
1982   verifyFormat("x = x! as (string);");
1983   verifyFormat("x = y! in z;");
1984   verifyFormat("var x = something.someFunction() as\n"
1985                "    something;",
1986                getGoogleJSStyleWithColumns(40));
1987 }
1988 
1989 TEST_F(FormatTestJS, TypeArguments) {
1990   verifyFormat("class X<Y> {}");
1991   verifyFormat("new X<Y>();");
1992   verifyFormat("foo<Y>(a);");
1993   verifyFormat("var x: X<Y>[];");
1994   verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
1995   verifyFormat("function f(a: List<any> = null) {}");
1996   verifyFormat("function f(): List<any> {}");
1997   verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n"
1998                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}");
1999   verifyFormat("function aaaaaaaaaa(\n"
2000                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n"
2001                "    aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n"
2002                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
2003 }
2004 
2005 TEST_F(FormatTestJS, UserDefinedTypeGuards) {
2006   verifyFormat(
2007       "function foo(check: Object):\n"
2008       "    check is {foo: string, bar: string, baz: string, foobar: string} {\n"
2009       "  return 'bar' in check;\n"
2010       "}\n");
2011 }
2012 
2013 TEST_F(FormatTestJS, OptionalTypes) {
2014   verifyFormat("function x(a?: b, c?, d?) {}");
2015   verifyFormat("class X {\n"
2016                "  y?: z;\n"
2017                "  z?;\n"
2018                "}");
2019   verifyFormat("interface X {\n"
2020                "  y?(): z;\n"
2021                "}");
2022   verifyFormat("constructor({aa}: {\n"
2023                "  aa?: string,\n"
2024                "  aaaaaaaa?: string,\n"
2025                "  aaaaaaaaaaaaaaa?: boolean,\n"
2026                "  aaaaaa?: List<string>\n"
2027                "}) {}");
2028 }
2029 
2030 TEST_F(FormatTestJS, IndexSignature) {
2031   verifyFormat("var x: {[k: string]: v};");
2032 }
2033 
2034 TEST_F(FormatTestJS, WrapAfterParen) {
2035   verifyFormat("xxxxxxxxxxx(\n"
2036                "    aaa, aaa);",
2037                getGoogleJSStyleWithColumns(20));
2038   verifyFormat("xxxxxxxxxxx(\n"
2039                "    aaa, aaa, aaa,\n"
2040                "    aaa, aaa, aaa);",
2041                getGoogleJSStyleWithColumns(20));
2042   verifyFormat("xxxxxxxxxxx(\n"
2043                "    aaaaaaaaaaaaaaaaaaaaaaaa,\n"
2044                "    function(x) {\n"
2045                "      y();  //\n"
2046                "    });",
2047                getGoogleJSStyleWithColumns(40));
2048   verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
2049                "       bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2050 }
2051 
2052 TEST_F(FormatTestJS, JSDocAnnotations) {
2053   verifyFormat("/**\n"
2054                " * @exports {this.is.a.long.path.to.a.Type}\n"
2055                " */",
2056                "/**\n"
2057                " * @exports {this.is.a.long.path.to.a.Type}\n"
2058                " */",
2059                getGoogleJSStyleWithColumns(20));
2060   verifyFormat("/**\n"
2061                " * @mods {this.is.a.long.path.to.a.Type}\n"
2062                " */",
2063                "/**\n"
2064                " * @mods {this.is.a.long.path.to.a.Type}\n"
2065                " */",
2066                getGoogleJSStyleWithColumns(20));
2067   verifyFormat("/**\n"
2068                " * @mods {this.is.a.long.path.to.a.Type}\n"
2069                " */",
2070                "/**\n"
2071                " * @mods {this.is.a.long.path.to.a.Type}\n"
2072                " */",
2073                getGoogleJSStyleWithColumns(20));
2074   verifyFormat("/**\n"
2075                " * @param {canWrap\n"
2076                " *     onSpace}\n"
2077                " */",
2078                "/**\n"
2079                " * @param {canWrap onSpace}\n"
2080                " */",
2081                getGoogleJSStyleWithColumns(20));
2082   // make sure clang-format doesn't break before *any* '{'
2083   verifyFormat("/**\n"
2084                " * @lala {lala {lalala\n"
2085                " */\n",
2086                "/**\n"
2087                " * @lala {lala {lalala\n"
2088                " */\n",
2089                getGoogleJSStyleWithColumns(20));
2090   verifyFormat("/**\n"
2091                " * @see http://very/very/long/url/is/long\n"
2092                " */",
2093                "/**\n"
2094                " * @see http://very/very/long/url/is/long\n"
2095                " */",
2096                getGoogleJSStyleWithColumns(20));
2097   verifyFormat(
2098       "/**\n"
2099       " * @param This is a\n"
2100       " *     long comment\n"
2101       " *     but no type\n"
2102       " */",
2103       "/**\n"
2104       " * @param This is a long comment but no type\n"
2105       " */",
2106       getGoogleJSStyleWithColumns(20));
2107   // Break and reindent @param line and reflow unrelated lines.
2108   EXPECT_EQ("{\n"
2109             "  /**\n"
2110             "   * long long long\n"
2111             "   * long\n"
2112             "   * @param {this.is.a.long.path.to.a.Type}\n"
2113             "   *     a\n"
2114             "   * long long long\n"
2115             "   * long long\n"
2116             "   */\n"
2117             "  function f(a) {}\n"
2118             "}",
2119             format("{\n"
2120                    "/**\n"
2121                    " * long long long long\n"
2122                    " * @param {this.is.a.long.path.to.a.Type} a\n"
2123                    " * long long long long\n"
2124                    " * long\n"
2125                    " */\n"
2126                    "  function f(a) {}\n"
2127                    "}",
2128                    getGoogleJSStyleWithColumns(20)));
2129 }
2130 
2131 TEST_F(FormatTestJS, RequoteStringsSingle) {
2132   verifyFormat("var x = 'foo';", "var x = \"foo\";");
2133   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";");
2134   verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";");
2135   verifyFormat(
2136       "var x =\n"
2137       "    'foo\\'';",
2138       // Code below is 15 chars wide, doesn't fit into the line with the
2139       // \ escape added.
2140       "var x = \"foo'\";", getGoogleJSStyleWithColumns(15));
2141   // Removes no-longer needed \ escape from ".
2142   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";");
2143   // Code below fits into 15 chars *after* removing the \ escape.
2144   verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";",
2145                getGoogleJSStyleWithColumns(15));
2146   verifyFormat("// clang-format off\n"
2147                "let x = \"double\";\n"
2148                "// clang-format on\n"
2149                "let x = 'single';\n",
2150                "// clang-format off\n"
2151                "let x = \"double\";\n"
2152                "// clang-format on\n"
2153                "let x = \"single\";\n");
2154 }
2155 
2156 TEST_F(FormatTestJS, RequoteAndIndent) {
2157   verifyFormat("let x = someVeryLongFunctionThatGoesOnAndOn(\n"
2158                "    'double quoted string that needs wrapping');",
2159                "let x = someVeryLongFunctionThatGoesOnAndOn("
2160                "\"double quoted string that needs wrapping\");");
2161 
2162   verifyFormat("let x =\n"
2163                "    'foo\\'oo';\n"
2164                "let x =\n"
2165                "    'foo\\'oo';",
2166                "let x=\"foo'oo\";\n"
2167                "let x=\"foo'oo\";",
2168                getGoogleJSStyleWithColumns(15));
2169 }
2170 
2171 TEST_F(FormatTestJS, RequoteStringsDouble) {
2172   FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2173   DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double;
2174   verifyFormat("var x = \"foo\";", DoubleQuotes);
2175   verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes);
2176   verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes);
2177 }
2178 
2179 TEST_F(FormatTestJS, RequoteStringsLeave) {
2180   FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
2181   LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave;
2182   verifyFormat("var x = \"foo\";", LeaveQuotes);
2183   verifyFormat("var x = 'foo';", LeaveQuotes);
2184 }
2185 
2186 TEST_F(FormatTestJS, SupportShebangLines) {
2187   verifyFormat("#!/usr/bin/env node\n"
2188                "var x = hello();",
2189                "#!/usr/bin/env node\n"
2190                "var x   =  hello();");
2191 }
2192 
2193 TEST_F(FormatTestJS, NonNullAssertionOperator) {
2194   verifyFormat("let x = foo!.bar();\n");
2195   verifyFormat("let x = foo ? bar! : baz;\n");
2196   verifyFormat("let x = !foo;\n");
2197   verifyFormat("if (!+a) {\n}");
2198   verifyFormat("let x = foo[0]!;\n");
2199   verifyFormat("let x = (foo)!;\n");
2200   verifyFormat("let x = x(foo!);\n");
2201   verifyFormat(
2202       "a.aaaaaa(a.a!).then(\n"
2203       "    x => x(x));\n",
2204       getGoogleJSStyleWithColumns(20));
2205   verifyFormat("let x = foo! - 1;\n");
2206   verifyFormat("let x = {foo: 1}!;\n");
2207   verifyFormat(
2208       "let x = hello.foo()!\n"
2209       "            .foo()!\n"
2210       "            .foo()!\n"
2211       "            .foo()!;\n",
2212       getGoogleJSStyleWithColumns(20));
2213   verifyFormat("let x = namespace!;\n");
2214   verifyFormat("return !!x;\n");
2215 }
2216 
2217 TEST_F(FormatTestJS, Conditional) {
2218   verifyFormat("y = x ? 1 : 2;");
2219   verifyFormat("x ? 1 : 2;");
2220   verifyFormat("class Foo {\n"
2221                "  field = true ? 1 : 2;\n"
2222                "  method(a = true ? 1 : 2) {}\n"
2223                "}");
2224 }
2225 
2226 TEST_F(FormatTestJS, ImportComments) {
2227   verifyFormat("import {x} from 'x';  // from some location",
2228                getGoogleJSStyleWithColumns(25));
2229   verifyFormat("// taze: x from 'location'", getGoogleJSStyleWithColumns(10));
2230   verifyFormat("/// <reference path=\"some/location\" />", getGoogleJSStyleWithColumns(10));
2231 }
2232 
2233 TEST_F(FormatTestJS, Exponentiation) {
2234   verifyFormat("squared = x ** 2;");
2235   verifyFormat("squared **= 2;");
2236 }
2237 
2238 TEST_F(FormatTestJS, NestedLiterals) {
2239   FormatStyle FourSpaces = getGoogleJSStyleWithColumns(15);
2240   FourSpaces.IndentWidth = 4;
2241   verifyFormat("var l = [\n"
2242                "    [\n"
2243                "        1,\n"
2244                "    ],\n"
2245                "];", FourSpaces);
2246   verifyFormat("var l = [\n"
2247                "    {\n"
2248                "        1: 1,\n"
2249                "    },\n"
2250                "];", FourSpaces);
2251   verifyFormat("someFunction(\n"
2252                "    p1,\n"
2253                "    [\n"
2254                "        1,\n"
2255                "    ],\n"
2256                ");", FourSpaces);
2257   verifyFormat("someFunction(\n"
2258                "    p1,\n"
2259                "    {\n"
2260                "        1: 1,\n"
2261                "    },\n"
2262                ");", FourSpaces);
2263   verifyFormat("var o = {\n"
2264                "    1: 1,\n"
2265                "    2: {\n"
2266                "        3: 3,\n"
2267                "    },\n"
2268                "};", FourSpaces);
2269   verifyFormat("var o = {\n"
2270                "    1: 1,\n"
2271                "    2: [\n"
2272                "        3,\n"
2273                "    ],\n"
2274                "};", FourSpaces);
2275 }
2276 
2277 TEST_F(FormatTestJS, BackslashesInComments) {
2278   verifyFormat("// hello \\\n"
2279                "if (x) foo();\n",
2280                "// hello \\\n"
2281                "     if ( x) \n"
2282                "   foo();\n");
2283   verifyFormat("/* ignore \\\n"
2284                " */\n"
2285                "if (x) foo();\n",
2286                "/* ignore \\\n"
2287                " */\n"
2288                " if (  x) foo();\n");
2289   verifyFormat("// st \\ art\\\n"
2290                "// comment"
2291                "// continue \\\n"
2292                "formatMe();\n",
2293                "// st \\ art\\\n"
2294                "// comment"
2295                "// continue \\\n"
2296                "formatMe( );\n");
2297 }
2298 
2299 TEST_F(FormatTestJS, AddsLastLinePenaltyIfEndingIsBroken) {
2300   EXPECT_EQ(
2301       "a = function() {\n"
2302       "  b = function() {\n"
2303       "    this.aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa] = aaaa.aaaaaa ?\n"
2304       "        aaaa.aaaaaa : /** @type "
2305       "{aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaaaaaaaa} */\n"
2306       "        (aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaa);\n"
2307       "  };\n"
2308       "};",
2309       format("a = function() {\n"
2310              "  b = function() {\n"
2311              "    this.aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa] = aaaa.aaaaaa ? "
2312              "aaaa.aaaaaa : /** @type "
2313              "{aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaaaaaaaa} */\n"
2314              "        (aaaa.aaaa.aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaa);\n"
2315              "  };\n"
2316              "};"));
2317 }
2318 
2319 TEST_F(FormatTestJS, ParameterNamingComment) {
2320   verifyFormat("callFoo(/*spaceAfterParameterNamingComment=*/ 1);");
2321 }
2322 
2323 TEST_F(FormatTestJS, ConditionalTypes) {
2324   // Formatting below is not necessarily intentional, this just ensures that
2325   // clang-format does not break the code.
2326   verifyFormat( // wrap
2327       "type UnionToIntersection<U> =\n"
2328       "    (U extends any ? (k: U) => void :\n"
2329       "                     never) extends((k: infer I) => void) ? I : never;");
2330 }
2331 
2332 } // end namespace tooling
2333 } // end namespace clang
2334