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