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