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 bool IncompleteFormat = false; 28 tooling::Replacements Replaces = 29 reformat(Style, Code, Ranges, "<stdin>", &IncompleteFormat); 30 EXPECT_FALSE(IncompleteFormat); 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, UnderstandsJavaScriptOperators) { 71 verifyFormat("a == = b;"); 72 verifyFormat("a != = b;"); 73 74 verifyFormat("a === b;"); 75 verifyFormat("aaaaaaa ===\n b;", getGoogleJSStyleWithColumns(10)); 76 verifyFormat("a !== b;"); 77 verifyFormat("aaaaaaa !==\n b;", getGoogleJSStyleWithColumns(10)); 78 verifyFormat("if (a + b + c +\n" 79 " d !==\n" 80 " e + f + g)\n" 81 " q();", 82 getGoogleJSStyleWithColumns(20)); 83 84 verifyFormat("a >> >= b;"); 85 86 verifyFormat("a >>> b;"); 87 verifyFormat("aaaaaaa >>>\n b;", getGoogleJSStyleWithColumns(10)); 88 verifyFormat("a >>>= b;"); 89 verifyFormat("aaaaaaa >>>=\n b;", getGoogleJSStyleWithColumns(10)); 90 verifyFormat("if (a + b + c +\n" 91 " d >>>\n" 92 " e + f + g)\n" 93 " q();", 94 getGoogleJSStyleWithColumns(20)); 95 verifyFormat("var x = aaaaaaaaaa ?\n" 96 " bbbbbb :\n" 97 " ccc;", 98 getGoogleJSStyleWithColumns(20)); 99 100 verifyFormat("var b = a.map((x) => x + 1);"); 101 verifyFormat("return ('aaa') in bbbb;"); 102 verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n" 103 " aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 104 FormatStyle Style = getGoogleJSStyleWithColumns(80); 105 Style.AlignOperands = true; 106 verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n" 107 " aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 108 Style); 109 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 110 verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa()\n" 111 " in aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 112 Style); 113 114 // ES6 spread operator. 115 verifyFormat("someFunction(...a);"); 116 verifyFormat("var x = [1, ...a, 2];"); 117 } 118 119 TEST_F(FormatTestJS, UnderstandsAmpAmp) { 120 verifyFormat("e && e.SomeFunction();"); 121 } 122 123 TEST_F(FormatTestJS, LiteralOperatorsCanBeKeywords) { 124 verifyFormat("not.and.or.not_eq = 1;"); 125 } 126 127 TEST_F(FormatTestJS, ReservedWords) { 128 // JavaScript reserved words (aka keywords) are only illegal when used as 129 // Identifiers, but are legal as IdentifierNames. 130 verifyFormat("x.class.struct = 1;"); 131 verifyFormat("x.case = 1;"); 132 verifyFormat("x.interface = 1;"); 133 verifyFormat("x.for = 1;"); 134 verifyFormat("x.of() = 1;"); 135 verifyFormat("x.in() = 1;"); 136 verifyFormat("x.let() = 1;"); 137 verifyFormat("x.var() = 1;"); 138 verifyFormat("x.for() = 1;"); 139 verifyFormat("x.as() = 1;"); 140 verifyFormat("x = {\n" 141 " a: 12,\n" 142 " interface: 1,\n" 143 " switch: 1,\n" 144 "};"); 145 verifyFormat("var struct = 2;"); 146 verifyFormat("var union = 2;"); 147 verifyFormat("var interface = 2;"); 148 verifyFormat("interface = 2;"); 149 verifyFormat("x = interface instanceof y;"); 150 } 151 152 TEST_F(FormatTestJS, ReservedWordsMethods) { 153 verifyFormat( 154 "class X {\n" 155 " delete() {\n" 156 " x();\n" 157 " }\n" 158 " interface() {\n" 159 " x();\n" 160 " }\n" 161 " let() {\n" 162 " x();\n" 163 " }\n" 164 "}\n"); 165 } 166 167 TEST_F(FormatTestJS, CppKeywords) { 168 // Make sure we don't mess stuff up because of C++ keywords. 169 verifyFormat("return operator && (aa);"); 170 } 171 172 TEST_F(FormatTestJS, ES6DestructuringAssignment) { 173 verifyFormat("var [a, b, c] = [1, 2, 3];"); 174 verifyFormat("const [a, b, c] = [1, 2, 3];"); 175 verifyFormat("let [a, b, c] = [1, 2, 3];"); 176 verifyFormat("var {a, b} = {a: 1, b: 2};"); 177 verifyFormat("let {a, b} = {a: 1, b: 2};"); 178 } 179 180 TEST_F(FormatTestJS, ContainerLiterals) { 181 verifyFormat("var x = {\n" 182 " y: function(a) {\n" 183 " return a;\n" 184 " }\n" 185 "};"); 186 verifyFormat("return {\n" 187 " link: function() {\n" 188 " f(); //\n" 189 " }\n" 190 "};"); 191 verifyFormat("return {\n" 192 " a: a,\n" 193 " link: function() {\n" 194 " f(); //\n" 195 " }\n" 196 "};"); 197 verifyFormat("return {\n" 198 " a: a,\n" 199 " link: function() {\n" 200 " f(); //\n" 201 " },\n" 202 " link: function() {\n" 203 " f(); //\n" 204 " }\n" 205 "};"); 206 verifyFormat("var stuff = {\n" 207 " // comment for update\n" 208 " update: false,\n" 209 " // comment for modules\n" 210 " modules: false,\n" 211 " // comment for tasks\n" 212 " tasks: false\n" 213 "};"); 214 verifyFormat("return {\n" 215 " 'finish':\n" 216 " //\n" 217 " a\n" 218 "};"); 219 verifyFormat("var obj = {\n" 220 " fooooooooo: function(x) {\n" 221 " return x.zIsTooLongForOneLineWithTheDeclarationLine();\n" 222 " }\n" 223 "};"); 224 // Simple object literal, as opposed to enum style below. 225 verifyFormat("var obj = {a: 123};"); 226 // Enum style top level assignment. 227 verifyFormat("X = {\n a: 123\n};"); 228 verifyFormat("X.Y = {\n a: 123\n};"); 229 // But only on the top level, otherwise its a plain object literal assignment. 230 verifyFormat("function x() {\n" 231 " y = {z: 1};\n" 232 "}"); 233 verifyFormat("x = foo && {a: 123};"); 234 235 // Arrow functions in object literals. 236 verifyFormat("var x = {\n" 237 " y: (a) => {\n" 238 " return a;\n" 239 " }\n" 240 "};"); 241 verifyFormat("var x = {y: (a) => a};"); 242 243 // Computed keys. 244 verifyFormat("var x = {[a]: 1, b: 2, [c]: 3};"); 245 verifyFormat("var x = {\n" 246 " [a]: 1,\n" 247 " b: 2,\n" 248 " [c]: 3,\n" 249 "};"); 250 251 // Object literals can leave out labels. 252 verifyFormat("f({a}, () => {\n" 253 " g(); //\n" 254 "});"); 255 256 // Keys can be quoted. 257 verifyFormat("var x = {\n" 258 " a: a,\n" 259 " b: b,\n" 260 " 'c': c,\n" 261 "};"); 262 263 // Dict literals can skip the label names. 264 verifyFormat("var x = {\n" 265 " aaa,\n" 266 " aaa,\n" 267 " aaa,\n" 268 "};"); 269 } 270 271 TEST_F(FormatTestJS, MethodsInObjectLiterals) { 272 verifyFormat("var o = {\n" 273 " value: 'test',\n" 274 " get value() { // getter\n" 275 " return this.value;\n" 276 " }\n" 277 "};"); 278 verifyFormat("var o = {\n" 279 " value: 'test',\n" 280 " set value(val) { // setter\n" 281 " this.value = val;\n" 282 " }\n" 283 "};"); 284 verifyFormat("var o = {\n" 285 " value: 'test',\n" 286 " someMethod(val) { // method\n" 287 " doSomething(this.value + val);\n" 288 " }\n" 289 "};"); 290 verifyFormat("var o = {\n" 291 " someMethod(val) { // method\n" 292 " doSomething(this.value + val);\n" 293 " },\n" 294 " someOtherMethod(val) { // method\n" 295 " doSomething(this.value + val);\n" 296 " }\n" 297 "};"); 298 } 299 300 TEST_F(FormatTestJS, SpacesInContainerLiterals) { 301 verifyFormat("var arr = [1, 2, 3];"); 302 verifyFormat("f({a: 1, b: 2, c: 3});"); 303 304 verifyFormat("var object_literal_with_long_name = {\n" 305 " a: 'aaaaaaaaaaaaaaaaaa',\n" 306 " b: 'bbbbbbbbbbbbbbbbbb'\n" 307 "};"); 308 309 verifyFormat("f({a: 1, b: 2, c: 3});", 310 getChromiumStyle(FormatStyle::LK_JavaScript)); 311 verifyFormat("f({'a': [{}]});"); 312 } 313 314 TEST_F(FormatTestJS, SingleQuotedStrings) { 315 verifyFormat("this.function('', true);"); 316 } 317 318 TEST_F(FormatTestJS, GoogScopes) { 319 verifyFormat("goog.scope(function() {\n" 320 "var x = a.b;\n" 321 "var y = c.d;\n" 322 "}); // goog.scope"); 323 verifyFormat("goog.scope(function() {\n" 324 "// test\n" 325 "var x = 0;\n" 326 "// test\n" 327 "});"); 328 } 329 330 TEST_F(FormatTestJS, GoogModules) { 331 verifyFormat("goog.module('this.is.really.absurdly.long');", 332 getGoogleJSStyleWithColumns(40)); 333 verifyFormat("goog.require('this.is.really.absurdly.long');", 334 getGoogleJSStyleWithColumns(40)); 335 verifyFormat("goog.provide('this.is.really.absurdly.long');", 336 getGoogleJSStyleWithColumns(40)); 337 verifyFormat("var long = goog.require('this.is.really.absurdly.long');", 338 getGoogleJSStyleWithColumns(40)); 339 verifyFormat("goog.setTestOnly('this.is.really.absurdly.long');", 340 getGoogleJSStyleWithColumns(40)); 341 verifyFormat("goog.forwardDeclare('this.is.really.absurdly.long');", 342 getGoogleJSStyleWithColumns(40)); 343 344 // These should be wrapped normally. 345 verifyFormat( 346 "var MyLongClassName =\n" 347 " goog.module.get('my.long.module.name.followedBy.MyLongClassName');"); 348 } 349 350 TEST_F(FormatTestJS, FormatsNamespaces) { 351 verifyFormat("namespace Foo {\n" 352 " export let x = 1;\n" 353 "}\n"); 354 verifyFormat("declare namespace Foo {\n" 355 " export let x: number;\n" 356 "}\n"); 357 } 358 359 TEST_F(FormatTestJS, NamespacesMayNotWrap) { 360 verifyFormat("declare namespace foobarbaz {\n" 361 "}\n", getGoogleJSStyleWithColumns(18)); 362 verifyFormat("declare module foobarbaz {\n" 363 "}\n", getGoogleJSStyleWithColumns(15)); 364 verifyFormat("namespace foobarbaz {\n" 365 "}\n", getGoogleJSStyleWithColumns(10)); 366 verifyFormat("module foobarbaz {\n" 367 "}\n", getGoogleJSStyleWithColumns(7)); 368 } 369 370 TEST_F(FormatTestJS, AmbientDeclarations) { 371 FormatStyle NineCols = getGoogleJSStyleWithColumns(9); 372 verifyFormat( 373 "declare class\n" 374 " X {}", 375 NineCols); 376 verifyFormat( 377 "declare function\n" 378 "x();", // TODO(martinprobst): should ideally be indented. 379 NineCols); 380 verifyFormat( 381 "declare enum X {\n" 382 "}", 383 NineCols); 384 verifyFormat( 385 "declare let\n" 386 " x: number;", 387 NineCols); 388 } 389 390 TEST_F(FormatTestJS, FormatsFreestandingFunctions) { 391 verifyFormat("function outer1(a, b) {\n" 392 " function inner1(a, b) {\n" 393 " return a;\n" 394 " }\n" 395 " inner1(a, b);\n" 396 "}\n" 397 "function outer2(a, b) {\n" 398 " function inner2(a, b) {\n" 399 " return a;\n" 400 " }\n" 401 " inner2(a, b);\n" 402 "}"); 403 verifyFormat("function f() {}"); 404 } 405 406 TEST_F(FormatTestJS, GeneratorFunctions) { 407 verifyFormat("function* f() {\n" 408 " let x = 1;\n" 409 " yield x;\n" 410 " yield* something();\n" 411 " yield [1, 2];\n" 412 " yield {a: 1};\n" 413 "}"); 414 verifyFormat("function*\n" 415 " f() {\n" 416 "}", 417 getGoogleJSStyleWithColumns(8)); 418 verifyFormat("export function* f() {\n" 419 " yield 1;\n" 420 "}\n"); 421 verifyFormat("class X {\n" 422 " * generatorMethod() {\n" 423 " yield x;\n" 424 " }\n" 425 "}"); 426 verifyFormat("var x = {\n" 427 " a: function*() {\n" 428 " //\n" 429 " }\n" 430 "}\n"); 431 } 432 433 TEST_F(FormatTestJS, AsyncFunctions) { 434 verifyFormat("async function f() {\n" 435 " let x = 1;\n" 436 " return fetch(x);\n" 437 "}"); 438 verifyFormat("async function* f() {\n" 439 " yield fetch(x);\n" 440 "}"); 441 verifyFormat("export async function f() {\n" 442 " return fetch(x);\n" 443 "}"); 444 verifyFormat("class X {\n" 445 " async asyncMethod() {\n" 446 " return fetch(1);\n" 447 " }\n" 448 "}"); 449 verifyFormat("function initialize() {\n" 450 " // Comment.\n" 451 " return async.then();\n" 452 "}\n"); 453 } 454 455 TEST_F(FormatTestJS, ArrayLiterals) { 456 verifyFormat("var aaaaa: List<SomeThing> =\n" 457 " [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];"); 458 verifyFormat("return [\n" 459 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 460 " ccccccccccccccccccccccccccc\n" 461 "];"); 462 verifyFormat("return [\n" 463 " aaaa().bbbbbbbb('A'),\n" 464 " aaaa().bbbbbbbb('B'),\n" 465 " aaaa().bbbbbbbb('C'),\n" 466 "];"); 467 verifyFormat("var someVariable = SomeFunction([\n" 468 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 469 " ccccccccccccccccccccccccccc\n" 470 "]);"); 471 verifyFormat("var someVariable = SomeFunction([\n" 472 " [aaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbb],\n" 473 "]);", 474 getGoogleJSStyleWithColumns(51)); 475 verifyFormat("var someVariable = SomeFunction(aaaa, [\n" 476 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 477 " ccccccccccccccccccccccccccc\n" 478 "]);"); 479 verifyFormat("var someVariable = SomeFunction(\n" 480 " aaaa,\n" 481 " [\n" 482 " aaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 483 " cccccccccccccccccccccccccc\n" 484 " ],\n" 485 " aaaa);"); 486 verifyFormat("var aaaa = aaaaa || // wrap\n" 487 " [];"); 488 489 verifyFormat("someFunction([], {a: a});"); 490 } 491 492 TEST_F(FormatTestJS, ColumnLayoutForArrayLiterals) { 493 verifyFormat("var array = [\n" 494 " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n" 495 " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n" 496 "];"); 497 verifyFormat("var array = someFunction([\n" 498 " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n" 499 " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n" 500 "]);"); 501 } 502 503 TEST_F(FormatTestJS, FunctionLiterals) { 504 FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript); 505 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 506 verifyFormat("doFoo(function() {});"); 507 verifyFormat("doFoo(function() { return 1; });", Style); 508 verifyFormat("var func = function() {\n" 509 " return 1;\n" 510 "};"); 511 verifyFormat("var func = //\n" 512 " function() {\n" 513 " return 1;\n" 514 "};"); 515 verifyFormat("return {\n" 516 " body: {\n" 517 " setAttribute: function(key, val) { this[key] = val; },\n" 518 " getAttribute: function(key) { return this[key]; },\n" 519 " style: {direction: ''}\n" 520 " }\n" 521 "};", 522 Style); 523 verifyFormat("abc = xyz ? function() {\n" 524 " return 1;\n" 525 "} : function() {\n" 526 " return -1;\n" 527 "};"); 528 529 verifyFormat("var closure = goog.bind(\n" 530 " function() { // comment\n" 531 " foo();\n" 532 " bar();\n" 533 " },\n" 534 " this, arg1IsReallyLongAndNeeedsLineBreaks,\n" 535 " arg3IsReallyLongAndNeeedsLineBreaks);"); 536 verifyFormat("var closure = goog.bind(function() { // comment\n" 537 " foo();\n" 538 " bar();\n" 539 "}, this);"); 540 verifyFormat("return {\n" 541 " a: 'E',\n" 542 " b: function() {\n" 543 " return function() {\n" 544 " f(); //\n" 545 " };\n" 546 " }\n" 547 "};"); 548 verifyFormat("{\n" 549 " var someVariable = function(x) {\n" 550 " return x.zIsTooLongForOneLineWithTheDeclarationLine();\n" 551 " };\n" 552 "}"); 553 verifyFormat("someLooooooooongFunction(\n" 554 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 555 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 556 " function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 557 " // code\n" 558 " });"); 559 560 verifyFormat("return {\n" 561 " a: function SomeFunction() {\n" 562 " // ...\n" 563 " return 1;\n" 564 " }\n" 565 "};"); 566 verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 567 " .then(goog.bind(function(aaaaaaaaaaa) {\n" 568 " someFunction();\n" 569 " someFunction();\n" 570 " }, this), aaaaaaaaaaaaaaaaa);"); 571 572 verifyFormat("someFunction(goog.bind(function() {\n" 573 " doSomething();\n" 574 " doSomething();\n" 575 "}, this), goog.bind(function() {\n" 576 " doSomething();\n" 577 " doSomething();\n" 578 "}, this));"); 579 580 // FIXME: This is bad, we should be wrapping before "function() {". 581 verifyFormat("someFunction(function() {\n" 582 " doSomething(); // break\n" 583 "})\n" 584 " .doSomethingElse(\n" 585 " // break\n" 586 " );"); 587 588 Style.ColumnLimit = 33; 589 verifyFormat("f({a: function() { return 1; }});", Style); 590 Style.ColumnLimit = 32; 591 verifyFormat("f({\n" 592 " a: function() { return 1; }\n" 593 "});", 594 Style); 595 596 } 597 598 TEST_F(FormatTestJS, InliningFunctionLiterals) { 599 FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript); 600 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 601 verifyFormat("var func = function() {\n" 602 " return 1;\n" 603 "};", 604 Style); 605 verifyFormat("var func = doSomething(function() { return 1; });", Style); 606 verifyFormat("var outer = function() {\n" 607 " var inner = function() { return 1; }\n" 608 "};", 609 Style); 610 verifyFormat("function outer1(a, b) {\n" 611 " function inner1(a, b) { return a; }\n" 612 "}", 613 Style); 614 615 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 616 verifyFormat("var func = function() { return 1; };", Style); 617 verifyFormat("var func = doSomething(function() { return 1; });", Style); 618 verifyFormat( 619 "var outer = function() { var inner = function() { return 1; } };", 620 Style); 621 verifyFormat("function outer1(a, b) {\n" 622 " function inner1(a, b) { return a; }\n" 623 "}", 624 Style); 625 626 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 627 verifyFormat("var func = function() {\n" 628 " return 1;\n" 629 "};", 630 Style); 631 verifyFormat("var func = doSomething(function() {\n" 632 " return 1;\n" 633 "});", 634 Style); 635 verifyFormat("var outer = function() {\n" 636 " var inner = function() {\n" 637 " return 1;\n" 638 " }\n" 639 "};", 640 Style); 641 verifyFormat("function outer1(a, b) {\n" 642 " function inner1(a, b) {\n" 643 " return a;\n" 644 " }\n" 645 "}", 646 Style); 647 648 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 649 verifyFormat("var func = function() {\n" 650 " return 1;\n" 651 "};", 652 Style); 653 } 654 655 TEST_F(FormatTestJS, MultipleFunctionLiterals) { 656 FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript); 657 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 658 verifyFormat("promise.then(\n" 659 " function success() {\n" 660 " doFoo();\n" 661 " doBar();\n" 662 " },\n" 663 " function error() {\n" 664 " doFoo();\n" 665 " doBaz();\n" 666 " },\n" 667 " []);\n"); 668 verifyFormat("promise.then(\n" 669 " function success() {\n" 670 " doFoo();\n" 671 " doBar();\n" 672 " },\n" 673 " [],\n" 674 " function error() {\n" 675 " doFoo();\n" 676 " doBaz();\n" 677 " });\n"); 678 verifyFormat("promise.then(\n" 679 " [],\n" 680 " function success() {\n" 681 " doFoo();\n" 682 " doBar();\n" 683 " },\n" 684 " function error() {\n" 685 " doFoo();\n" 686 " doBaz();\n" 687 " });\n"); 688 689 verifyFormat("getSomeLongPromise()\n" 690 " .then(function(value) { body(); })\n" 691 " .thenCatch(function(error) {\n" 692 " body();\n" 693 " body();\n" 694 " });", 695 Style); 696 verifyFormat("getSomeLongPromise()\n" 697 " .then(function(value) {\n" 698 " body();\n" 699 " body();\n" 700 " })\n" 701 " .thenCatch(function(error) {\n" 702 " body();\n" 703 " body();\n" 704 " });"); 705 706 verifyFormat("getSomeLongPromise()\n" 707 " .then(function(value) { body(); })\n" 708 " .thenCatch(function(error) { body(); });", 709 Style); 710 711 verifyFormat("return [aaaaaaaaaaaaaaaaaaaaaa]\n" 712 " .aaaaaaa(function() {\n" 713 " //\n" 714 " })\n" 715 " .bbbbbb();"); 716 } 717 718 TEST_F(FormatTestJS, ArrowFunctions) { 719 verifyFormat("var x = (a) => {\n" 720 " return a;\n" 721 "};"); 722 verifyFormat("var x = (a) => {\n" 723 " function y() {\n" 724 " return 42;\n" 725 " }\n" 726 " return a;\n" 727 "};"); 728 verifyFormat("var x = (a: type): {some: type} => {\n" 729 " return a;\n" 730 "};"); 731 verifyFormat("var x = (a) => a;"); 732 verifyFormat("return () => [];"); 733 verifyFormat("var aaaaaaaaaaaaaaaaaaaa = {\n" 734 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 735 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 736 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) =>\n" 737 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 738 "};"); 739 verifyFormat("var a = a.aaaaaaa(\n" 740 " (a: a) => aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) &&\n" 741 " aaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbb));"); 742 verifyFormat("var a = a.aaaaaaa(\n" 743 " (a: a) => aaaaaaaaaaaaaaaaaaaaa(bbbbbbbbb) ?\n" 744 " aaaaaaaaaaaaaaaaaaaaa(bbbbbbb) :\n" 745 " aaaaaaaaaaaaaaaaaaaaa(bbbbbbb));"); 746 747 // FIXME: This is bad, we should be wrapping before "() => {". 748 verifyFormat("someFunction(() => {\n" 749 " doSomething(); // break\n" 750 "})\n" 751 " .doSomethingElse(\n" 752 " // break\n" 753 " );"); 754 } 755 756 TEST_F(FormatTestJS, ReturnStatements) { 757 verifyFormat("function() {\n" 758 " return [hello, world];\n" 759 "}"); 760 } 761 762 TEST_F(FormatTestJS, ForLoops) { 763 verifyFormat("for (var i in [2, 3]) {\n" 764 "}"); 765 verifyFormat("for (var i of [2, 3]) {\n" 766 "}"); 767 verifyFormat("for (let {a, b} of x) {\n" 768 "}"); 769 verifyFormat("for (let {a, b} in x) {\n" 770 "}"); 771 } 772 773 TEST_F(FormatTestJS, WrapRespectsAutomaticSemicolonInsertion) { 774 // The following statements must not wrap, as otherwise the program meaning 775 // would change due to automatic semicolon insertion. 776 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1. 777 verifyFormat("return aaaaa;", getGoogleJSStyleWithColumns(10)); 778 verifyFormat("return /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10)); 779 verifyFormat("continue aaaaa;", getGoogleJSStyleWithColumns(10)); 780 verifyFormat("continue /* hello! */ aaaaa;", getGoogleJSStyleWithColumns(10)); 781 verifyFormat("break aaaaa;", getGoogleJSStyleWithColumns(10)); 782 verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10)); 783 verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10)); 784 verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10)); 785 verifyFormat("return [\n" 786 " aaa\n" 787 "];", 788 getGoogleJSStyleWithColumns(12)); 789 } 790 791 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) { 792 verifyFormat("a\n" 793 "b;", 794 " a \n" 795 " b ;"); 796 verifyFormat("a()\n" 797 "b;", 798 " a ()\n" 799 " b ;"); 800 verifyFormat("a[b]\n" 801 "c;", 802 "a [b]\n" 803 "c ;"); 804 verifyFormat("1\n" 805 "a;", 806 "1 \n" 807 "a ;"); 808 verifyFormat("a\n" 809 "1;", 810 "a \n" 811 "1 ;"); 812 verifyFormat("a\n" 813 "'x';", 814 "a \n" 815 " 'x';"); 816 verifyFormat("a++\n" 817 "b;", 818 "a ++\n" 819 "b ;"); 820 verifyFormat("a\n" 821 "!b && c;", 822 "a \n" 823 " ! b && c;"); 824 verifyFormat("a\n" 825 "if (1) f();", 826 " a\n" 827 " if (1) f();"); 828 verifyFormat("a\n" 829 "class X {}", 830 " a\n" 831 " class X {}"); 832 verifyFormat("var a", "var\n" 833 "a"); 834 verifyFormat("x instanceof String", "x\n" 835 "instanceof\n" 836 "String"); 837 verifyFormat("function f(@Foo bar) {}", "function f(@Foo\n" 838 " bar) {}"); 839 verifyFormat("a = true\n" 840 "return 1", 841 "a = true\n" 842 " return 1"); 843 verifyFormat("a = 's'\n" 844 "return 1", 845 "a = 's'\n" 846 " return 1"); 847 verifyFormat("a = null\n" 848 "return 1", 849 "a = null\n" 850 " return 1"); 851 } 852 853 TEST_F(FormatTestJS, ClosureStyleCasts) { 854 verifyFormat("var x = /** @type {foo} */ (bar);"); 855 } 856 857 TEST_F(FormatTestJS, TryCatch) { 858 verifyFormat("try {\n" 859 " f();\n" 860 "} catch (e) {\n" 861 " g();\n" 862 "} finally {\n" 863 " h();\n" 864 "}"); 865 866 // But, of course, "catch" is a perfectly fine function name in JavaScript. 867 verifyFormat("someObject.catch();"); 868 verifyFormat("someObject.new();"); 869 verifyFormat("someObject.delete();"); 870 } 871 872 TEST_F(FormatTestJS, StringLiteralConcatenation) { 873 verifyFormat("var literal = 'hello ' +\n" 874 " 'world';"); 875 } 876 877 TEST_F(FormatTestJS, RegexLiteralClassification) { 878 // Regex literals. 879 verifyFormat("var regex = /abc/;"); 880 verifyFormat("f(/abc/);"); 881 verifyFormat("f(abc, /abc/);"); 882 verifyFormat("some_map[/abc/];"); 883 verifyFormat("var x = a ? /abc/ : /abc/;"); 884 verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}"); 885 verifyFormat("var x = !/abc/.test(y);"); 886 verifyFormat("var x = a && /abc/.test(y);"); 887 verifyFormat("var x = a || /abc/.test(y);"); 888 verifyFormat("var x = a + /abc/.search(y);"); 889 verifyFormat("/abc/.search(y);"); 890 verifyFormat("var regexs = {/abc/, /abc/};"); 891 verifyFormat("return /abc/;"); 892 893 // Not regex literals. 894 verifyFormat("var a = a / 2 + b / 3;"); 895 verifyFormat("var a = a++ / 2;"); 896 // Prefix unary can operate on regex literals, not that it makes sense. 897 verifyFormat("var a = ++/a/;"); 898 899 // This is a known issue, regular expressions are incorrectly detected if 900 // directly following a closing parenthesis. 901 verifyFormat("if (foo) / bar /.exec(baz);"); 902 } 903 904 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) { 905 verifyFormat("var regex = /=/;"); 906 verifyFormat("var regex = /a*/;"); 907 verifyFormat("var regex = /a+/;"); 908 verifyFormat("var regex = /a?/;"); 909 verifyFormat("var regex = /.a./;"); 910 verifyFormat("var regex = /a\\*/;"); 911 verifyFormat("var regex = /^a$/;"); 912 verifyFormat("var regex = /\\/a/;"); 913 verifyFormat("var regex = /(?:x)/;"); 914 verifyFormat("var regex = /x(?=y)/;"); 915 verifyFormat("var regex = /x(?!y)/;"); 916 verifyFormat("var regex = /x|y/;"); 917 verifyFormat("var regex = /a{2}/;"); 918 verifyFormat("var regex = /a{1,3}/;"); 919 920 verifyFormat("var regex = /[abc]/;"); 921 verifyFormat("var regex = /[^abc]/;"); 922 verifyFormat("var regex = /[\\b]/;"); 923 verifyFormat("var regex = /[/]/;"); 924 verifyFormat("var regex = /[\\/]/;"); 925 verifyFormat("var regex = /\\[/;"); 926 verifyFormat("var regex = /\\\\[/]/;"); 927 verifyFormat("var regex = /}[\"]/;"); 928 verifyFormat("var regex = /}[/\"]/;"); 929 verifyFormat("var regex = /}[\"/]/;"); 930 931 verifyFormat("var regex = /\\b/;"); 932 verifyFormat("var regex = /\\B/;"); 933 verifyFormat("var regex = /\\d/;"); 934 verifyFormat("var regex = /\\D/;"); 935 verifyFormat("var regex = /\\f/;"); 936 verifyFormat("var regex = /\\n/;"); 937 verifyFormat("var regex = /\\r/;"); 938 verifyFormat("var regex = /\\s/;"); 939 verifyFormat("var regex = /\\S/;"); 940 verifyFormat("var regex = /\\t/;"); 941 verifyFormat("var regex = /\\v/;"); 942 verifyFormat("var regex = /\\w/;"); 943 verifyFormat("var regex = /\\W/;"); 944 verifyFormat("var regex = /a(a)\\1/;"); 945 verifyFormat("var regex = /\\0/;"); 946 verifyFormat("var regex = /\\\\/g;"); 947 verifyFormat("var regex = /\\a\\\\/g;"); 948 verifyFormat("var regex = /\a\\//g;"); 949 verifyFormat("var regex = /a\\//;\n" 950 "var x = 0;"); 951 verifyFormat("var regex = /'/g;", "var regex = /'/g ;"); 952 verifyFormat("var regex = /'/g; //'", "var regex = /'/g ; //'"); 953 verifyFormat("var regex = /\\/*/;\n" 954 "var x = 0;", 955 "var regex = /\\/*/;\n" 956 "var x=0;"); 957 verifyFormat("var x = /a\\//;", "var x = /a\\// \n;"); 958 verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16)); 959 verifyFormat("var regex =\n" 960 " /\"/;", 961 getGoogleJSStyleWithColumns(15)); 962 verifyFormat("var regex = //\n" 963 " /a/;"); 964 verifyFormat("var regexs = [\n" 965 " /d/, //\n" 966 " /aa/, //\n" 967 "];"); 968 } 969 970 TEST_F(FormatTestJS, RegexLiteralModifiers) { 971 verifyFormat("var regex = /abc/g;"); 972 verifyFormat("var regex = /abc/i;"); 973 verifyFormat("var regex = /abc/m;"); 974 verifyFormat("var regex = /abc/y;"); 975 } 976 977 TEST_F(FormatTestJS, RegexLiteralLength) { 978 verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;", 979 getGoogleJSStyleWithColumns(60)); 980 verifyFormat("var regex =\n" 981 " /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;", 982 getGoogleJSStyleWithColumns(60)); 983 verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;", 984 getGoogleJSStyleWithColumns(50)); 985 } 986 987 TEST_F(FormatTestJS, RegexLiteralExamples) { 988 verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);"); 989 } 990 991 TEST_F(FormatTestJS, TypeAnnotations) { 992 verifyFormat("var x: string;"); 993 verifyFormat("var x: {a: string; b: number;} = {};"); 994 verifyFormat("function x(): string {\n return 'x';\n}"); 995 verifyFormat("function x(): {x: string} {\n return {x: 'x'};\n}"); 996 verifyFormat("function x(y: string): string {\n return 'x';\n}"); 997 verifyFormat("for (var y: string in x) {\n x();\n}"); 998 verifyFormat("for (var y: string of x) {\n x();\n}"); 999 verifyFormat("function x(y: {a?: number;} = {}): number {\n" 1000 " return 12;\n" 1001 "}"); 1002 verifyFormat("((a: string, b: number): string => a + b);"); 1003 verifyFormat("var x: (y: number) => string;"); 1004 verifyFormat("var x: P<string, (a: number) => string>;"); 1005 verifyFormat("var x = {\n" 1006 " y: function(): z {\n" 1007 " return 1;\n" 1008 " }\n" 1009 "};"); 1010 verifyFormat("var x = {\n" 1011 " y: function(): {a: number} {\n" 1012 " return 1;\n" 1013 " }\n" 1014 "};"); 1015 verifyFormat("function someFunc(args: string[]):\n" 1016 " {longReturnValue: string[]} {}", 1017 getGoogleJSStyleWithColumns(60)); 1018 } 1019 1020 TEST_F(FormatTestJS, UnionIntersectionTypes) { 1021 verifyFormat("let x: A|B = A | B;"); 1022 verifyFormat("let x: A&B|C = A & B;"); 1023 verifyFormat("let x: Foo<A|B> = new Foo<A|B>();"); 1024 verifyFormat("function(x: A|B): C&D {}"); 1025 verifyFormat("function(x: A|B = A | B): C&D {}"); 1026 verifyFormat("function x(path: number|string) {}"); 1027 verifyFormat("function x(): string|number {}"); 1028 verifyFormat("type Foo = Bar|Baz;"); 1029 verifyFormat("type Foo = Bar<X>|Baz;"); 1030 verifyFormat("type Foo = (Bar<X>|Baz);"); 1031 verifyFormat("let x: Bar|Baz;"); 1032 verifyFormat("let x: Bar<X>|Baz;"); 1033 verifyFormat("let x: (Foo|Bar)[];"); 1034 } 1035 1036 TEST_F(FormatTestJS, ClassDeclarations) { 1037 verifyFormat("class C {\n x: string = 12;\n}"); 1038 verifyFormat("class C {\n x(): string => 12;\n}"); 1039 verifyFormat("class C {\n ['x' + 2]: string = 12;\n}"); 1040 verifyFormat("class C {\n private x: string = 12;\n}"); 1041 verifyFormat("class C {\n private static x: string = 12;\n}"); 1042 verifyFormat("class C {\n static x(): string {\n return 'asd';\n }\n}"); 1043 verifyFormat("class C extends P implements I {}"); 1044 verifyFormat("class C extends p.P implements i.I {}"); 1045 verifyFormat("class Test {\n" 1046 " aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n" 1047 " aaaaaaaaaaaaaaaaaaaaaa {}\n" 1048 "}"); 1049 verifyFormat("foo = class Name {\n" 1050 " constructor() {}\n" 1051 "};"); 1052 verifyFormat("foo = class {\n" 1053 " constructor() {}\n" 1054 "};"); 1055 verifyFormat("class C {\n" 1056 " x: {y: Z;} = {};\n" 1057 " private y: {y: Z;} = {};\n" 1058 "}"); 1059 1060 // ':' is not a type declaration here. 1061 verifyFormat("class X {\n" 1062 " subs = {\n" 1063 " 'b': {\n" 1064 " 'c': 1,\n" 1065 " },\n" 1066 " };\n" 1067 "}"); 1068 verifyFormat("@Component({\n" 1069 " moduleId: module.id,\n" 1070 "})\n" 1071 "class SessionListComponent implements OnDestroy, OnInit {\n" 1072 "}"); 1073 } 1074 1075 TEST_F(FormatTestJS, InterfaceDeclarations) { 1076 verifyFormat("interface I {\n" 1077 " x: string;\n" 1078 " enum: string[];\n" 1079 " enum?: string[];\n" 1080 "}\n" 1081 "var y;"); 1082 // Ensure that state is reset after parsing the interface. 1083 verifyFormat("interface a {}\n" 1084 "export function b() {}\n" 1085 "var x;"); 1086 1087 // Arrays of object type literals. 1088 verifyFormat("interface I {\n" 1089 " o: {}[];\n" 1090 "}"); 1091 } 1092 1093 TEST_F(FormatTestJS, EnumDeclarations) { 1094 verifyFormat("enum Foo {\n" 1095 " A = 1,\n" 1096 " B\n" 1097 "}"); 1098 verifyFormat("export /* somecomment*/ enum Foo {\n" 1099 " A = 1,\n" 1100 " B\n" 1101 "}"); 1102 verifyFormat("enum Foo {\n" 1103 " A = 1, // comment\n" 1104 " B\n" 1105 "}\n" 1106 "var x = 1;"); 1107 } 1108 1109 TEST_F(FormatTestJS, MetadataAnnotations) { 1110 verifyFormat("@A\nclass C {\n}"); 1111 verifyFormat("@A({arg: 'value'})\nclass C {\n}"); 1112 verifyFormat("@A\n@B\nclass C {\n}"); 1113 verifyFormat("class C {\n @A x: string;\n}"); 1114 verifyFormat("class C {\n" 1115 " @A\n" 1116 " private x(): string {\n" 1117 " return 'y';\n" 1118 " }\n" 1119 "}"); 1120 verifyFormat("class C {\n" 1121 " private x(@A x: string) {}\n" 1122 "}"); 1123 verifyFormat("class X {}\n" 1124 "class Y {}"); 1125 } 1126 1127 TEST_F(FormatTestJS, TypeAliases) { 1128 verifyFormat("type X = number;\n" 1129 "class C {}"); 1130 verifyFormat("type X<Y> = Z<Y>;"); 1131 verifyFormat("type X = {\n" 1132 " y: number\n" 1133 "};\n" 1134 "class C {}"); 1135 } 1136 1137 TEST_F(FormatTestJS, Modules) { 1138 verifyFormat("import SomeThing from 'some/module.js';"); 1139 verifyFormat("import {X, Y} from 'some/module.js';"); 1140 verifyFormat("import a, {X, Y} from 'some/module.js';"); 1141 verifyFormat("import {X, Y,} from 'some/module.js';"); 1142 verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';"); 1143 // Ensure Automatic Semicolon Insertion does not break on "as\n". 1144 verifyFormat("import {X as myX} from 'm';", "import {X as\n" 1145 " myX} from 'm';"); 1146 verifyFormat("import * as lib from 'some/module.js';"); 1147 verifyFormat("var x = {import: 1};\nx.import = 2;"); 1148 1149 verifyFormat("export function fn() {\n" 1150 " return 'fn';\n" 1151 "}"); 1152 verifyFormat("export function A() {}\n" 1153 "export default function B() {}\n" 1154 "export function C() {}"); 1155 verifyFormat("export default () => {\n" 1156 " let x = 1;\n" 1157 " return x;\n" 1158 "}"); 1159 verifyFormat("export const x = 12;"); 1160 verifyFormat("export default class X {}"); 1161 verifyFormat("export {X, Y} from 'some/module.js';"); 1162 verifyFormat("export {X, Y,} from 'some/module.js';"); 1163 verifyFormat("export {SomeVeryLongExport as X, " 1164 "SomeOtherVeryLongExport as Y} from 'some/module.js';"); 1165 // export without 'from' is wrapped. 1166 verifyFormat("export let someRatherLongVariableName =\n" 1167 " someSurprisinglyLongVariable + someOtherRatherLongVar;"); 1168 // ... but not if from is just an identifier. 1169 verifyFormat("export {\n" 1170 " from as from,\n" 1171 " someSurprisinglyLongVariable as\n" 1172 " from\n" 1173 "};", 1174 getGoogleJSStyleWithColumns(20)); 1175 verifyFormat("export class C {\n" 1176 " x: number;\n" 1177 " y: string;\n" 1178 "}"); 1179 verifyFormat("export class X { y: number; }"); 1180 verifyFormat("export abstract class X { y: number; }"); 1181 verifyFormat("export default class X { y: number }"); 1182 verifyFormat("export default function() {\n return 1;\n}"); 1183 verifyFormat("export var x = 12;"); 1184 verifyFormat("class C {}\n" 1185 "export function f() {}\n" 1186 "var v;"); 1187 verifyFormat("export var x: number = 12;"); 1188 verifyFormat("export const y = {\n" 1189 " a: 1,\n" 1190 " b: 2\n" 1191 "};"); 1192 verifyFormat("export enum Foo {\n" 1193 " BAR,\n" 1194 " // adsdasd\n" 1195 " BAZ\n" 1196 "}"); 1197 verifyFormat("export default [\n" 1198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 1199 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 1200 "];"); 1201 verifyFormat("export default [];"); 1202 verifyFormat("export default () => {};"); 1203 verifyFormat("export interface Foo { foo: number; }\n" 1204 "export class Bar {\n" 1205 " blah(): string {\n" 1206 " return this.blah;\n" 1207 " };\n" 1208 "}"); 1209 } 1210 1211 TEST_F(FormatTestJS, ImportWrapping) { 1212 verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying," 1213 " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying" 1214 "} from 'some/module.js';"); 1215 FormatStyle Style = getGoogleJSStyleWithColumns(80); 1216 Style.JavaScriptWrapImports = true; 1217 verifyFormat("import {\n" 1218 " VeryLongImportsAreAnnoying,\n" 1219 " VeryLongImportsAreAnnoying,\n" 1220 " VeryLongImportsAreAnnoying,\n" 1221 "} from 'some/module.js';", 1222 Style); 1223 verifyFormat("import {\n" 1224 " A,\n" 1225 " A,\n" 1226 "} from 'some/module.js';", 1227 Style); 1228 verifyFormat("export {\n" 1229 " A,\n" 1230 " A,\n" 1231 "} from 'some/module.js';", 1232 Style); 1233 } 1234 1235 TEST_F(FormatTestJS, TemplateStrings) { 1236 // Keeps any whitespace/indentation within the template string. 1237 verifyFormat("var x = `hello\n" 1238 " ${name}\n" 1239 " !`;", 1240 "var x = `hello\n" 1241 " ${ name }\n" 1242 " !`;"); 1243 1244 verifyFormat("var x =\n" 1245 " `hello ${world}` >= some();", 1246 getGoogleJSStyleWithColumns(34)); // Barely doesn't fit. 1247 verifyFormat("var x = `hello ${world}` >= some();", 1248 getGoogleJSStyleWithColumns(35)); // Barely fits. 1249 verifyFormat("var x = `hellö ${wörld}` >= söme();", 1250 getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8. 1251 verifyFormat("var x = `hello\n" 1252 " ${world}` >=\n" 1253 " some();", 1254 "var x =\n" 1255 " `hello\n" 1256 " ${world}` >= some();", 1257 getGoogleJSStyleWithColumns(21)); // Barely doesn't fit. 1258 verifyFormat("var x = `hello\n" 1259 " ${world}` >= some();", 1260 "var x =\n" 1261 " `hello\n" 1262 " ${world}` >= some();", 1263 getGoogleJSStyleWithColumns(22)); // Barely fits. 1264 1265 verifyFormat("var x =\n" 1266 " `h`;", 1267 getGoogleJSStyleWithColumns(11)); 1268 verifyFormat("var x =\n `multi\n line`;", "var x = `multi\n line`;", 1269 getGoogleJSStyleWithColumns(13)); 1270 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1271 " `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);"); 1272 // Repro for an obscure width-miscounting issue with template strings. 1273 verifyFormat( 1274 "someLongVariable =\n" 1275 " " 1276 "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;", 1277 "someLongVariable = " 1278 "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;"); 1279 1280 // Make sure template strings get a proper ColumnWidth assigned, even if they 1281 // are first token in line. 1282 verifyFormat( 1283 "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 1284 " `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;"); 1285 1286 // Two template strings. 1287 verifyFormat("var x = `hello` == `hello`;"); 1288 1289 // Comments in template strings. 1290 verifyFormat("var x = `//a`;\n" 1291 "var y;", 1292 "var x =\n `//a`;\n" 1293 "var y ;"); 1294 verifyFormat("var x = `/*a`;\n" 1295 "var y;", 1296 "var x =\n `/*a`;\n" 1297 "var y;"); 1298 // Unterminated string literals in a template string. 1299 verifyFormat("var x = `'`; // comment with matching quote '\n" 1300 "var y;"); 1301 verifyFormat("var x = `\"`; // comment with matching quote \"\n" 1302 "var y;"); 1303 verifyFormat("it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa);", 1304 "it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa) ;", 1305 getGoogleJSStyleWithColumns(40)); 1306 // Backticks in a comment - not a template string. 1307 verifyFormat("var x = 1 // `/*a`;\n" 1308 " ;", 1309 "var x =\n 1 // `/*a`;\n" 1310 " ;"); 1311 verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */"); 1312 // Comment spans multiple template strings. 1313 verifyFormat("var x = `/*a`;\n" 1314 "var y = ` */ `;", 1315 "var x =\n `/*a`;\n" 1316 "var y =\n ` */ `;"); 1317 // Escaped backtick. 1318 verifyFormat("var x = ` \\` a`;\n" 1319 "var y;", 1320 "var x = ` \\` a`;\n" 1321 "var y;"); 1322 // Escaped dollar. 1323 verifyFormat("var x = ` \\${foo}`;\n"); 1324 } 1325 1326 TEST_F(FormatTestJS, TemplateStringASI) { 1327 verifyFormat("var x = `hello${world}`;", "var x = `hello${\n" 1328 " world\n" 1329 "}`;"); 1330 } 1331 1332 TEST_F(FormatTestJS, NestedTemplateStrings) { 1333 verifyFormat( 1334 "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;"); 1335 verifyFormat("var x = `he${({text: 'll'}.text)}o`;"); 1336 1337 // Crashed at some point. 1338 verifyFormat("}"); 1339 } 1340 1341 TEST_F(FormatTestJS, TaggedTemplateStrings) { 1342 verifyFormat("var x = html`<ul>`;"); 1343 } 1344 1345 TEST_F(FormatTestJS, CastSyntax) { 1346 verifyFormat("var x = <type>foo;"); 1347 verifyFormat("var x = foo as type;"); 1348 verifyFormat("let x = (a + b) as\n" 1349 " LongTypeIsLong;", 1350 getGoogleJSStyleWithColumns(20)); 1351 verifyFormat("foo = <Bar[]>[\n" 1352 " 1, //\n" 1353 " 2\n" 1354 "];"); 1355 verifyFormat("var x = [{x: 1} as type];"); 1356 verifyFormat("x = x as [a, b];"); 1357 verifyFormat("x = x as {a: string};"); 1358 verifyFormat("x = x as (string);"); 1359 verifyFormat("x = x! as (string);"); 1360 } 1361 1362 TEST_F(FormatTestJS, TypeArguments) { 1363 verifyFormat("class X<Y> {}"); 1364 verifyFormat("new X<Y>();"); 1365 verifyFormat("foo<Y>(a);"); 1366 verifyFormat("var x: X<Y>[];"); 1367 verifyFormat("class C extends D<E> implements F<G>, H<I> {}"); 1368 verifyFormat("function f(a: List<any> = null) {}"); 1369 verifyFormat("function f(): List<any> {}"); 1370 verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n" 1371 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}"); 1372 verifyFormat("function aaaaaaaaaa(\n" 1373 " aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n" 1374 " aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n" 1375 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}"); 1376 } 1377 1378 TEST_F(FormatTestJS, UserDefinedTypeGuards) { 1379 verifyFormat( 1380 "function foo(check: Object):\n" 1381 " check is {foo: string, bar: string, baz: string, foobar: string} {\n" 1382 " return 'bar' in check;\n" 1383 "}\n"); 1384 } 1385 1386 TEST_F(FormatTestJS, OptionalTypes) { 1387 verifyFormat("function x(a?: b, c?, d?) {}"); 1388 verifyFormat("class X {\n" 1389 " y?: z;\n" 1390 " z?;\n" 1391 "}"); 1392 verifyFormat("interface X {\n" 1393 " y?(): z;\n" 1394 "}"); 1395 verifyFormat("constructor({aa}: {\n" 1396 " aa?: string,\n" 1397 " aaaaaaaa?: string,\n" 1398 " aaaaaaaaaaaaaaa?: boolean,\n" 1399 " aaaaaa?: List<string>\n" 1400 "}) {}"); 1401 } 1402 1403 TEST_F(FormatTestJS, IndexSignature) { 1404 verifyFormat("var x: {[k: string]: v};"); 1405 } 1406 1407 TEST_F(FormatTestJS, WrapAfterParen) { 1408 verifyFormat("xxxxxxxxxxx(\n" 1409 " aaa, aaa);", 1410 getGoogleJSStyleWithColumns(20)); 1411 verifyFormat("xxxxxxxxxxx(\n" 1412 " aaa, aaa, aaa,\n" 1413 " aaa, aaa, aaa);", 1414 getGoogleJSStyleWithColumns(20)); 1415 verifyFormat("xxxxxxxxxxx(\n" 1416 " aaaaaaaaaaaaaaaaaaaaaaaa,\n" 1417 " function(x) {\n" 1418 " y(); //\n" 1419 " });", 1420 getGoogleJSStyleWithColumns(40)); 1421 verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 1422 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 1423 } 1424 1425 TEST_F(FormatTestJS, JSDocAnnotations) { 1426 verifyFormat("/**\n" 1427 " * @export {this.is.a.long.path.to.a.Type}\n" 1428 " */", 1429 "/**\n" 1430 " * @export {this.is.a.long.path.to.a.Type}\n" 1431 " */", 1432 getGoogleJSStyleWithColumns(20)); 1433 } 1434 1435 TEST_F(FormatTestJS, RequoteStringsSingle) { 1436 verifyFormat("var x = 'foo';", "var x = \"foo\";"); 1437 verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";"); 1438 verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";"); 1439 verifyFormat( 1440 "var x =\n" 1441 " 'foo\\'';", 1442 // Code below is 15 chars wide, doesn't fit into the line with the 1443 // \ escape added. 1444 "var x = \"foo'\";", getGoogleJSStyleWithColumns(15)); 1445 // Removes no-longer needed \ escape from ". 1446 verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";"); 1447 // Code below fits into 15 chars *after* removing the \ escape. 1448 verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";", 1449 getGoogleJSStyleWithColumns(15)); 1450 verifyFormat("// clang-format off\n" 1451 "let x = \"double\";\n" 1452 "// clang-format on\n" 1453 "let x = 'single';\n", 1454 "// clang-format off\n" 1455 "let x = \"double\";\n" 1456 "// clang-format on\n" 1457 "let x = \"single\";\n"); 1458 } 1459 1460 TEST_F(FormatTestJS, RequoteAndIndent) { 1461 verifyFormat("let x = someVeryLongFunctionThatGoesOnAndOn(\n" 1462 " 'double quoted string that needs wrapping');", 1463 "let x = someVeryLongFunctionThatGoesOnAndOn(" 1464 "\"double quoted string that needs wrapping\");"); 1465 1466 verifyFormat("let x =\n" 1467 " 'foo\\'oo';\n" 1468 "let x =\n" 1469 " 'foo\\'oo';", 1470 "let x=\"foo'oo\";\n" 1471 "let x=\"foo'oo\";", 1472 getGoogleJSStyleWithColumns(15)); 1473 } 1474 1475 TEST_F(FormatTestJS, RequoteStringsDouble) { 1476 FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript); 1477 DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double; 1478 verifyFormat("var x = \"foo\";", DoubleQuotes); 1479 verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes); 1480 verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes); 1481 } 1482 1483 TEST_F(FormatTestJS, RequoteStringsLeave) { 1484 FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript); 1485 LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave; 1486 verifyFormat("var x = \"foo\";", LeaveQuotes); 1487 verifyFormat("var x = 'foo';", LeaveQuotes); 1488 } 1489 1490 TEST_F(FormatTestJS, SupportShebangLines) { 1491 verifyFormat("#!/usr/bin/env node\n" 1492 "var x = hello();", 1493 "#!/usr/bin/env node\n" 1494 "var x = hello();"); 1495 } 1496 1497 TEST_F(FormatTestJS, NonNullAssertionOperator) { 1498 verifyFormat("let x = foo!.bar();\n"); 1499 verifyFormat("let x = foo ? bar! : baz;\n"); 1500 verifyFormat("let x = !foo;\n"); 1501 verifyFormat("let x = foo[0]!;\n"); 1502 verifyFormat("let x = (foo)!;\n"); 1503 verifyFormat("let x = foo! - 1;\n"); 1504 verifyFormat("let x = {foo: 1}!;\n"); 1505 } 1506 1507 TEST_F(FormatTestJS, Conditional) { 1508 verifyFormat("y = x ? 1 : 2;"); 1509 verifyFormat("x ? 1 : 2;"); 1510 verifyFormat("class Foo {\n" 1511 " field = true ? 1 : 2;\n" 1512 " method(a = true ? 1 : 2) {}\n" 1513 "}"); 1514 } 1515 1516 TEST_F(FormatTestJS, ImportComments) { 1517 verifyFormat("import {x} from 'x'; // from some location", 1518 getGoogleJSStyleWithColumns(25)); 1519 verifyFormat("// taze: x from 'location'", getGoogleJSStyleWithColumns(10)); 1520 } 1521 1522 } // end namespace tooling 1523 } // end namespace clang 1524