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