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