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