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