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