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