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