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