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