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