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