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