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