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