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, ClassDeclarations) { 1367 verifyFormat("class C {\n x: string = 12;\n}"); 1368 verifyFormat("class C {\n x(): string => 12;\n}"); 1369 verifyFormat("class C {\n ['x' + 2]: string = 12;\n}"); 1370 verifyFormat("class C {\n" 1371 " foo() {}\n" 1372 " [bar]() {}\n" 1373 "}\n"); 1374 verifyFormat("class C {\n private x: string = 12;\n}"); 1375 verifyFormat("class C {\n private static x: string = 12;\n}"); 1376 verifyFormat("class C {\n static x(): string {\n return 'asd';\n }\n}"); 1377 verifyFormat("class C extends P implements I {}"); 1378 verifyFormat("class C extends p.P implements i.I {}"); 1379 verifyFormat( 1380 "x(class {\n" 1381 " a(): A {}\n" 1382 "});"); 1383 verifyFormat("class Test {\n" 1384 " aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n" 1385 " aaaaaaaaaaaaaaaaaaaaaa {}\n" 1386 "}"); 1387 verifyFormat("foo = class Name {\n" 1388 " constructor() {}\n" 1389 "};"); 1390 verifyFormat("foo = class {\n" 1391 " constructor() {}\n" 1392 "};"); 1393 verifyFormat("class C {\n" 1394 " x: {y: Z;} = {};\n" 1395 " private y: {y: Z;} = {};\n" 1396 "}"); 1397 1398 // ':' is not a type declaration here. 1399 verifyFormat("class X {\n" 1400 " subs = {\n" 1401 " 'b': {\n" 1402 " 'c': 1,\n" 1403 " },\n" 1404 " };\n" 1405 "}"); 1406 verifyFormat("@Component({\n" 1407 " moduleId: module.id,\n" 1408 "})\n" 1409 "class SessionListComponent implements OnDestroy, OnInit {\n" 1410 "}"); 1411 } 1412 1413 TEST_F(FormatTestJS, InterfaceDeclarations) { 1414 verifyFormat("interface I {\n" 1415 " x: string;\n" 1416 " enum: string[];\n" 1417 " enum?: string[];\n" 1418 "}\n" 1419 "var y;"); 1420 // Ensure that state is reset after parsing the interface. 1421 verifyFormat("interface a {}\n" 1422 "export function b() {}\n" 1423 "var x;"); 1424 1425 // Arrays of object type literals. 1426 verifyFormat("interface I {\n" 1427 " o: {}[];\n" 1428 "}"); 1429 } 1430 1431 TEST_F(FormatTestJS, ObjectTypesInExtendsImplements) { 1432 verifyFormat("class C extends {} {}"); 1433 verifyFormat("class C implements {bar: number} {}"); 1434 // Somewhat odd, but probably closest to reasonable formatting? 1435 verifyFormat("class C implements {\n" 1436 " bar: number,\n" 1437 " baz: string,\n" 1438 "} {}"); 1439 verifyFormat("class C<P extends {}> {}"); 1440 } 1441 1442 TEST_F(FormatTestJS, EnumDeclarations) { 1443 verifyFormat("enum Foo {\n" 1444 " A = 1,\n" 1445 " B\n" 1446 "}"); 1447 verifyFormat("export /* somecomment*/ enum Foo {\n" 1448 " A = 1,\n" 1449 " B\n" 1450 "}"); 1451 verifyFormat("enum Foo {\n" 1452 " A = 1, // comment\n" 1453 " B\n" 1454 "}\n" 1455 "var x = 1;"); 1456 verifyFormat("const enum Foo {\n" 1457 " A = 1,\n" 1458 " B\n" 1459 "}"); 1460 verifyFormat("export const enum Foo {\n" 1461 " A = 1,\n" 1462 " B\n" 1463 "}"); 1464 } 1465 1466 TEST_F(FormatTestJS, MetadataAnnotations) { 1467 verifyFormat("@A\nclass C {\n}"); 1468 verifyFormat("@A({arg: 'value'})\nclass C {\n}"); 1469 verifyFormat("@A\n@B\nclass C {\n}"); 1470 verifyFormat("class C {\n @A x: string;\n}"); 1471 verifyFormat("class C {\n" 1472 " @A\n" 1473 " private x(): string {\n" 1474 " return 'y';\n" 1475 " }\n" 1476 "}"); 1477 verifyFormat("class C {\n" 1478 " private x(@A x: string) {}\n" 1479 "}"); 1480 verifyFormat("class X {}\n" 1481 "class Y {}"); 1482 verifyFormat("class X {\n" 1483 " @property() private isReply = false;\n" 1484 "}\n"); 1485 } 1486 1487 TEST_F(FormatTestJS, TypeAliases) { 1488 verifyFormat("type X = number;\n" 1489 "class C {}"); 1490 verifyFormat("type X<Y> = Z<Y>;"); 1491 verifyFormat("type X = {\n" 1492 " y: number\n" 1493 "};\n" 1494 "class C {}"); 1495 } 1496 1497 TEST_F(FormatTestJS, TypeInterfaceLineWrapping) { 1498 const FormatStyle &Style = getGoogleJSStyleWithColumns(20); 1499 verifyFormat("type LongTypeIsReallyUnreasonablyLong =\n" 1500 " string;\n", 1501 "type LongTypeIsReallyUnreasonablyLong = string;\n", 1502 Style); 1503 verifyFormat( 1504 "interface AbstractStrategyFactoryProvider {\n" 1505 " a: number\n" 1506 "}\n", 1507 "interface AbstractStrategyFactoryProvider { a: number }\n", 1508 Style); 1509 } 1510 1511 TEST_F(FormatTestJS, Modules) { 1512 verifyFormat("import SomeThing from 'some/module.js';"); 1513 verifyFormat("import {X, Y} from 'some/module.js';"); 1514 verifyFormat("import a, {X, Y} from 'some/module.js';"); 1515 verifyFormat("import {X, Y,} from 'some/module.js';"); 1516 verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';"); 1517 // Ensure Automatic Semicolon Insertion does not break on "as\n". 1518 verifyFormat("import {X as myX} from 'm';", "import {X as\n" 1519 " myX} from 'm';"); 1520 verifyFormat("import * as lib from 'some/module.js';"); 1521 verifyFormat("var x = {import: 1};\nx.import = 2;"); 1522 1523 verifyFormat("export function fn() {\n" 1524 " return 'fn';\n" 1525 "}"); 1526 verifyFormat("export function A() {}\n" 1527 "export default function B() {}\n" 1528 "export function C() {}"); 1529 verifyFormat("export default () => {\n" 1530 " let x = 1;\n" 1531 " return x;\n" 1532 "}"); 1533 verifyFormat("export const x = 12;"); 1534 verifyFormat("export default class X {}"); 1535 verifyFormat("export {X, Y} from 'some/module.js';"); 1536 verifyFormat("export {X, Y,} from 'some/module.js';"); 1537 verifyFormat("export {SomeVeryLongExport as X, " 1538 "SomeOtherVeryLongExport as Y} from 'some/module.js';"); 1539 // export without 'from' is wrapped. 1540 verifyFormat("export let someRatherLongVariableName =\n" 1541 " someSurprisinglyLongVariable + someOtherRatherLongVar;"); 1542 // ... but not if from is just an identifier. 1543 verifyFormat("export {\n" 1544 " from as from,\n" 1545 " someSurprisinglyLongVariable as\n" 1546 " from\n" 1547 "};", 1548 getGoogleJSStyleWithColumns(20)); 1549 verifyFormat("export class C {\n" 1550 " x: number;\n" 1551 " y: string;\n" 1552 "}"); 1553 verifyFormat("export class X { y: number; }"); 1554 verifyFormat("export abstract class X { y: number; }"); 1555 verifyFormat("export default class X { y: number }"); 1556 verifyFormat("export default function() {\n return 1;\n}"); 1557 verifyFormat("export var x = 12;"); 1558 verifyFormat("class C {}\n" 1559 "export function f() {}\n" 1560 "var v;"); 1561 verifyFormat("export var x: number = 12;"); 1562 verifyFormat("export const y = {\n" 1563 " a: 1,\n" 1564 " b: 2\n" 1565 "};"); 1566 verifyFormat("export enum Foo {\n" 1567 " BAR,\n" 1568 " // adsdasd\n" 1569 " BAZ\n" 1570 "}"); 1571 verifyFormat("export default [\n" 1572 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 1573 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 1574 "];"); 1575 verifyFormat("export default [];"); 1576 verifyFormat("export default () => {};"); 1577 verifyFormat("export interface Foo { foo: number; }\n" 1578 "export class Bar {\n" 1579 " blah(): string {\n" 1580 " return this.blah;\n" 1581 " };\n" 1582 "}"); 1583 } 1584 1585 TEST_F(FormatTestJS, ImportWrapping) { 1586 verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying," 1587 " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying" 1588 "} from 'some/module.js';"); 1589 FormatStyle Style = getGoogleJSStyleWithColumns(80); 1590 Style.JavaScriptWrapImports = true; 1591 verifyFormat("import {\n" 1592 " VeryLongImportsAreAnnoying,\n" 1593 " VeryLongImportsAreAnnoying,\n" 1594 " VeryLongImportsAreAnnoying,\n" 1595 "} from 'some/module.js';", 1596 Style); 1597 verifyFormat("import {\n" 1598 " A,\n" 1599 " A,\n" 1600 "} from 'some/module.js';", 1601 Style); 1602 verifyFormat("export {\n" 1603 " A,\n" 1604 " A,\n" 1605 "} from 'some/module.js';", 1606 Style); 1607 Style.ColumnLimit = 40; 1608 // Using this version of verifyFormat because test::messUp hides the issue. 1609 verifyFormat("import {\n" 1610 " A,\n" 1611 "} from\n" 1612 " 'some/path/longer/than/column/limit/module.js';", 1613 " import { \n" 1614 " A, \n" 1615 " } from\n" 1616 " 'some/path/longer/than/column/limit/module.js' ; ", 1617 Style); 1618 } 1619 1620 TEST_F(FormatTestJS, TemplateStrings) { 1621 // Keeps any whitespace/indentation within the template string. 1622 verifyFormat("var x = `hello\n" 1623 " ${name}\n" 1624 " !`;", 1625 "var x = `hello\n" 1626 " ${ name }\n" 1627 " !`;"); 1628 1629 verifyFormat("var x =\n" 1630 " `hello ${world}` >= some();", 1631 getGoogleJSStyleWithColumns(34)); // Barely doesn't fit. 1632 verifyFormat("var x = `hello ${world}` >= some();", 1633 getGoogleJSStyleWithColumns(35)); // Barely fits. 1634 verifyFormat("var x = `hellö ${wörld}` >= söme();", 1635 getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8. 1636 verifyFormat("var x = `hello\n" 1637 " ${world}` >=\n" 1638 " some();", 1639 "var x =\n" 1640 " `hello\n" 1641 " ${world}` >= some();", 1642 getGoogleJSStyleWithColumns(21)); // Barely doesn't fit. 1643 verifyFormat("var x = `hello\n" 1644 " ${world}` >= some();", 1645 "var x =\n" 1646 " `hello\n" 1647 " ${world}` >= some();", 1648 getGoogleJSStyleWithColumns(22)); // Barely fits. 1649 1650 verifyFormat("var x =\n" 1651 " `h`;", 1652 getGoogleJSStyleWithColumns(11)); 1653 verifyFormat("var x =\n `multi\n line`;", "var x = `multi\n line`;", 1654 getGoogleJSStyleWithColumns(13)); 1655 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1656 " `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);"); 1657 // Repro for an obscure width-miscounting issue with template strings. 1658 verifyFormat( 1659 "someLongVariable =\n" 1660 " " 1661 "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;", 1662 "someLongVariable = " 1663 "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;"); 1664 1665 // Make sure template strings get a proper ColumnWidth assigned, even if they 1666 // are first token in line. 1667 verifyFormat( 1668 "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 1669 " `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;"); 1670 1671 // Two template strings. 1672 verifyFormat("var x = `hello` == `hello`;"); 1673 1674 // Comments in template strings. 1675 verifyFormat("var x = `//a`;\n" 1676 "var y;", 1677 "var x =\n `//a`;\n" 1678 "var y ;"); 1679 verifyFormat("var x = `/*a`;\n" 1680 "var y;", 1681 "var x =\n `/*a`;\n" 1682 "var y;"); 1683 // Unterminated string literals in a template string. 1684 verifyFormat("var x = `'`; // comment with matching quote '\n" 1685 "var y;"); 1686 verifyFormat("var x = `\"`; // comment with matching quote \"\n" 1687 "var y;"); 1688 verifyFormat("it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa);", 1689 "it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa) ;", 1690 getGoogleJSStyleWithColumns(40)); 1691 // Backticks in a comment - not a template string. 1692 verifyFormat("var x = 1 // `/*a`;\n" 1693 " ;", 1694 "var x =\n 1 // `/*a`;\n" 1695 " ;"); 1696 verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */"); 1697 // Comment spans multiple template strings. 1698 verifyFormat("var x = `/*a`;\n" 1699 "var y = ` */ `;", 1700 "var x =\n `/*a`;\n" 1701 "var y =\n ` */ `;"); 1702 // Escaped backtick. 1703 verifyFormat("var x = ` \\` a`;\n" 1704 "var y;", 1705 "var x = ` \\` a`;\n" 1706 "var y;"); 1707 // Escaped dollar. 1708 verifyFormat("var x = ` \\${foo}`;\n"); 1709 1710 // The token stream can contain two string_literals in sequence, but that 1711 // doesn't mean that they are implicitly concatenated in JavaScript. 1712 verifyFormat("var f = `aaaa ${a ? 'a' : 'b'}`;"); 1713 1714 // Ensure that scopes are appropriately set around evaluated expressions in 1715 // template strings. 1716 verifyFormat("var f = `aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa\n" 1717 " aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`;", 1718 "var f = `aaaaaaaaaaaaa:${aaaaaaa. aaaaa} aaaaaaaa\n" 1719 " aaaaaaaaaaaaa:${ aaaaaaa. aaaaa} aaaaaaaa`;"); 1720 verifyFormat("var x = someFunction(`${})`) //\n" 1721 " .oooooooooooooooooon();"); 1722 verifyFormat("var x = someFunction(`${aaaa}${\n" 1723 " aaaaa( //\n" 1724 " aaaaa)\n" 1725 " })`);"); 1726 } 1727 1728 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) { 1729 verifyFormat("var f = `aaaaaaaaaaaaaaaaaa: ${\n" 1730 " aaaaa + //\n" 1731 " bbbb\n" 1732 " }`;", 1733 "var f = `aaaaaaaaaaaaaaaaaa: ${aaaaa + //\n" 1734 " bbbb}`;"); 1735 verifyFormat("var f = `\n" 1736 " aaaaaaaaaaaaaaaaaa: ${\n" 1737 " aaaaa + //\n" 1738 " bbbb\n" 1739 " }`;", 1740 "var f = `\n" 1741 " aaaaaaaaaaaaaaaaaa: ${ aaaaa + //\n" 1742 " bbbb }`;"); 1743 verifyFormat("var f = `\n" 1744 " aaaaaaaaaaaaaaaaaa: ${\n" 1745 " someFunction(\n" 1746 " aaaaa + //\n" 1747 " bbbb)\n" 1748 " }`;", 1749 "var f = `\n" 1750 " aaaaaaaaaaaaaaaaaa: ${someFunction (\n" 1751 " aaaaa + //\n" 1752 " bbbb)}`;"); 1753 1754 // It might be preferable to wrap before "someFunction". 1755 verifyFormat("var f = `\n" 1756 " aaaaaaaaaaaaaaaaaa: ${someFunction({\n" 1757 " aaaa: aaaaa,\n" 1758 " bbbb: bbbbb,\n" 1759 " })}`;", 1760 "var f = `\n" 1761 " aaaaaaaaaaaaaaaaaa: ${someFunction ({\n" 1762 " aaaa: aaaaa,\n" 1763 " bbbb: bbbbb,\n" 1764 " })}`;"); 1765 } 1766 1767 TEST_F(FormatTestJS, TemplateStringASI) { 1768 verifyFormat("var x = `hello${world}`;", "var x = `hello${\n" 1769 " world\n" 1770 "}`;"); 1771 } 1772 1773 TEST_F(FormatTestJS, NestedTemplateStrings) { 1774 verifyFormat( 1775 "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;"); 1776 verifyFormat("var x = `he${({text: 'll'}.text)}o`;"); 1777 1778 // Crashed at some point. 1779 verifyFormat("}"); 1780 } 1781 1782 TEST_F(FormatTestJS, TaggedTemplateStrings) { 1783 verifyFormat("var x = html`<ul>`;"); 1784 verifyFormat("yield `hello`;"); 1785 } 1786 1787 TEST_F(FormatTestJS, CastSyntax) { 1788 verifyFormat("var x = <type>foo;"); 1789 verifyFormat("var x = foo as type;"); 1790 verifyFormat("let x = (a + b) as\n" 1791 " LongTypeIsLong;", 1792 getGoogleJSStyleWithColumns(20)); 1793 verifyFormat("foo = <Bar[]>[\n" 1794 " 1, //\n" 1795 " 2\n" 1796 "];"); 1797 verifyFormat("var x = [{x: 1} as type];"); 1798 verifyFormat("x = x as [a, b];"); 1799 verifyFormat("x = x as {a: string};"); 1800 verifyFormat("x = x as (string);"); 1801 verifyFormat("x = x! as (string);"); 1802 verifyFormat("var x = something.someFunction() as\n" 1803 " something;", 1804 getGoogleJSStyleWithColumns(40)); 1805 } 1806 1807 TEST_F(FormatTestJS, TypeArguments) { 1808 verifyFormat("class X<Y> {}"); 1809 verifyFormat("new X<Y>();"); 1810 verifyFormat("foo<Y>(a);"); 1811 verifyFormat("var x: X<Y>[];"); 1812 verifyFormat("class C extends D<E> implements F<G>, H<I> {}"); 1813 verifyFormat("function f(a: List<any> = null) {}"); 1814 verifyFormat("function f(): List<any> {}"); 1815 verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n" 1816 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}"); 1817 verifyFormat("function aaaaaaaaaa(\n" 1818 " aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n" 1819 " aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n" 1820 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}"); 1821 } 1822 1823 TEST_F(FormatTestJS, UserDefinedTypeGuards) { 1824 verifyFormat( 1825 "function foo(check: Object):\n" 1826 " check is {foo: string, bar: string, baz: string, foobar: string} {\n" 1827 " return 'bar' in check;\n" 1828 "}\n"); 1829 } 1830 1831 TEST_F(FormatTestJS, OptionalTypes) { 1832 verifyFormat("function x(a?: b, c?, d?) {}"); 1833 verifyFormat("class X {\n" 1834 " y?: z;\n" 1835 " z?;\n" 1836 "}"); 1837 verifyFormat("interface X {\n" 1838 " y?(): z;\n" 1839 "}"); 1840 verifyFormat("constructor({aa}: {\n" 1841 " aa?: string,\n" 1842 " aaaaaaaa?: string,\n" 1843 " aaaaaaaaaaaaaaa?: boolean,\n" 1844 " aaaaaa?: List<string>\n" 1845 "}) {}"); 1846 } 1847 1848 TEST_F(FormatTestJS, IndexSignature) { 1849 verifyFormat("var x: {[k: string]: v};"); 1850 } 1851 1852 TEST_F(FormatTestJS, WrapAfterParen) { 1853 verifyFormat("xxxxxxxxxxx(\n" 1854 " aaa, aaa);", 1855 getGoogleJSStyleWithColumns(20)); 1856 verifyFormat("xxxxxxxxxxx(\n" 1857 " aaa, aaa, aaa,\n" 1858 " aaa, aaa, aaa);", 1859 getGoogleJSStyleWithColumns(20)); 1860 verifyFormat("xxxxxxxxxxx(\n" 1861 " aaaaaaaaaaaaaaaaaaaaaaaa,\n" 1862 " function(x) {\n" 1863 " y(); //\n" 1864 " });", 1865 getGoogleJSStyleWithColumns(40)); 1866 verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 1867 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 1868 } 1869 1870 TEST_F(FormatTestJS, JSDocAnnotations) { 1871 verifyFormat("/**\n" 1872 " * @export {this.is.a.long.path.to.a.Type}\n" 1873 " */", 1874 "/**\n" 1875 " * @export {this.is.a.long.path.to.a.Type}\n" 1876 " */", 1877 getGoogleJSStyleWithColumns(20)); 1878 verifyFormat("/**\n" 1879 " * @mods {this.is.a.long.path.to.a.Type}\n" 1880 " */", 1881 "/**\n" 1882 " * @mods {this.is.a.long.path.to.a.Type}\n" 1883 " */", 1884 getGoogleJSStyleWithColumns(20)); 1885 verifyFormat("/**\n" 1886 " * @param {this.is.a.long.path.to.a.Type}\n" 1887 " */", 1888 "/**\n" 1889 " * @param {this.is.a.long.path.to.a.Type}\n" 1890 " */", 1891 getGoogleJSStyleWithColumns(20)); 1892 verifyFormat("/**\n" 1893 " * @see http://very/very/long/url/is/long\n" 1894 " */", 1895 "/**\n" 1896 " * @see http://very/very/long/url/is/long\n" 1897 " */", 1898 getGoogleJSStyleWithColumns(20)); 1899 verifyFormat( 1900 "/**\n" 1901 " * @param This is a\n" 1902 " * long comment but\n" 1903 " * no type\n" 1904 " */", 1905 "/**\n" 1906 " * @param This is a long comment but no type\n" 1907 " */", 1908 getGoogleJSStyleWithColumns(20)); 1909 // Don't break @param line, but reindent it and reflow unrelated lines. 1910 verifyFormat("{\n" 1911 " /**\n" 1912 " * long long long\n" 1913 " * long\n" 1914 " * @param {this.is.a.long.path.to.a.Type} a\n" 1915 " * long long long\n" 1916 " * long long\n" 1917 " */\n" 1918 " function f(a) {}\n" 1919 "}", 1920 "{\n" 1921 "/**\n" 1922 " * long long long long\n" 1923 " * @param {this.is.a.long.path.to.a.Type} a\n" 1924 " * long long long long\n" 1925 " * long\n" 1926 " */\n" 1927 " function f(a) {}\n" 1928 "}", 1929 getGoogleJSStyleWithColumns(20)); 1930 } 1931 1932 TEST_F(FormatTestJS, RequoteStringsSingle) { 1933 verifyFormat("var x = 'foo';", "var x = \"foo\";"); 1934 verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";"); 1935 verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";"); 1936 verifyFormat( 1937 "var x =\n" 1938 " 'foo\\'';", 1939 // Code below is 15 chars wide, doesn't fit into the line with the 1940 // \ escape added. 1941 "var x = \"foo'\";", getGoogleJSStyleWithColumns(15)); 1942 // Removes no-longer needed \ escape from ". 1943 verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";"); 1944 // Code below fits into 15 chars *after* removing the \ escape. 1945 verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";", 1946 getGoogleJSStyleWithColumns(15)); 1947 verifyFormat("// clang-format off\n" 1948 "let x = \"double\";\n" 1949 "// clang-format on\n" 1950 "let x = 'single';\n", 1951 "// clang-format off\n" 1952 "let x = \"double\";\n" 1953 "// clang-format on\n" 1954 "let x = \"single\";\n"); 1955 } 1956 1957 TEST_F(FormatTestJS, RequoteAndIndent) { 1958 verifyFormat("let x = someVeryLongFunctionThatGoesOnAndOn(\n" 1959 " 'double quoted string that needs wrapping');", 1960 "let x = someVeryLongFunctionThatGoesOnAndOn(" 1961 "\"double quoted string that needs wrapping\");"); 1962 1963 verifyFormat("let x =\n" 1964 " 'foo\\'oo';\n" 1965 "let x =\n" 1966 " 'foo\\'oo';", 1967 "let x=\"foo'oo\";\n" 1968 "let x=\"foo'oo\";", 1969 getGoogleJSStyleWithColumns(15)); 1970 } 1971 1972 TEST_F(FormatTestJS, RequoteStringsDouble) { 1973 FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript); 1974 DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double; 1975 verifyFormat("var x = \"foo\";", DoubleQuotes); 1976 verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes); 1977 verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes); 1978 } 1979 1980 TEST_F(FormatTestJS, RequoteStringsLeave) { 1981 FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript); 1982 LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave; 1983 verifyFormat("var x = \"foo\";", LeaveQuotes); 1984 verifyFormat("var x = 'foo';", LeaveQuotes); 1985 } 1986 1987 TEST_F(FormatTestJS, SupportShebangLines) { 1988 verifyFormat("#!/usr/bin/env node\n" 1989 "var x = hello();", 1990 "#!/usr/bin/env node\n" 1991 "var x = hello();"); 1992 } 1993 1994 TEST_F(FormatTestJS, NonNullAssertionOperator) { 1995 verifyFormat("let x = foo!.bar();\n"); 1996 verifyFormat("let x = foo ? bar! : baz;\n"); 1997 verifyFormat("let x = !foo;\n"); 1998 verifyFormat("let x = foo[0]!;\n"); 1999 verifyFormat("let x = (foo)!;\n"); 2000 verifyFormat("let x = x(foo!);\n"); 2001 verifyFormat( 2002 "a.aaaaaa(a.a!).then(\n" 2003 " x => x(x));\n", 2004 getGoogleJSStyleWithColumns(20)); 2005 verifyFormat("let x = foo! - 1;\n"); 2006 verifyFormat("let x = {foo: 1}!;\n"); 2007 verifyFormat( 2008 "let x = hello.foo()!\n" 2009 " .foo()!\n" 2010 " .foo()!\n" 2011 " .foo()!;\n", 2012 getGoogleJSStyleWithColumns(20)); 2013 verifyFormat("let x = namespace!;\n"); 2014 verifyFormat("return !!x;\n"); 2015 } 2016 2017 TEST_F(FormatTestJS, Conditional) { 2018 verifyFormat("y = x ? 1 : 2;"); 2019 verifyFormat("x ? 1 : 2;"); 2020 verifyFormat("class Foo {\n" 2021 " field = true ? 1 : 2;\n" 2022 " method(a = true ? 1 : 2) {}\n" 2023 "}"); 2024 } 2025 2026 TEST_F(FormatTestJS, ImportComments) { 2027 verifyFormat("import {x} from 'x'; // from some location", 2028 getGoogleJSStyleWithColumns(25)); 2029 verifyFormat("// taze: x from 'location'", getGoogleJSStyleWithColumns(10)); 2030 verifyFormat("/// <reference path=\"some/location\" />", getGoogleJSStyleWithColumns(10)); 2031 } 2032 2033 TEST_F(FormatTestJS, Exponentiation) { 2034 verifyFormat("squared = x ** 2;"); 2035 verifyFormat("squared **= 2;"); 2036 } 2037 2038 TEST_F(FormatTestJS, NestedLiterals) { 2039 FormatStyle FourSpaces = getGoogleJSStyleWithColumns(15); 2040 FourSpaces.IndentWidth = 4; 2041 verifyFormat("var l = [\n" 2042 " [\n" 2043 " 1,\n" 2044 " ],\n" 2045 "];", FourSpaces); 2046 verifyFormat("var l = [\n" 2047 " {\n" 2048 " 1: 1,\n" 2049 " },\n" 2050 "];", FourSpaces); 2051 verifyFormat("someFunction(\n" 2052 " p1,\n" 2053 " [\n" 2054 " 1,\n" 2055 " ],\n" 2056 ");", FourSpaces); 2057 verifyFormat("someFunction(\n" 2058 " p1,\n" 2059 " {\n" 2060 " 1: 1,\n" 2061 " },\n" 2062 ");", FourSpaces); 2063 verifyFormat("var o = {\n" 2064 " 1: 1,\n" 2065 " 2: {\n" 2066 " 3: 3,\n" 2067 " },\n" 2068 "};", FourSpaces); 2069 verifyFormat("var o = {\n" 2070 " 1: 1,\n" 2071 " 2: [\n" 2072 " 3,\n" 2073 " ],\n" 2074 "};", FourSpaces); 2075 } 2076 2077 } // end namespace tooling 2078 } // end namespace clang 2079