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