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