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