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