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