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