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