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