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