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