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("class Test {\n" 1113 " aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n" 1114 " aaaaaaaaaaaaaaaaaaaaaa {}\n" 1115 "}"); 1116 verifyFormat("foo = class Name {\n" 1117 " constructor() {}\n" 1118 "};"); 1119 verifyFormat("foo = class {\n" 1120 " constructor() {}\n" 1121 "};"); 1122 verifyFormat("class C {\n" 1123 " x: {y: Z;} = {};\n" 1124 " private y: {y: Z;} = {};\n" 1125 "}"); 1126 1127 // ':' is not a type declaration here. 1128 verifyFormat("class X {\n" 1129 " subs = {\n" 1130 " 'b': {\n" 1131 " 'c': 1,\n" 1132 " },\n" 1133 " };\n" 1134 "}"); 1135 verifyFormat("@Component({\n" 1136 " moduleId: module.id,\n" 1137 "})\n" 1138 "class SessionListComponent implements OnDestroy, OnInit {\n" 1139 "}"); 1140 } 1141 1142 TEST_F(FormatTestJS, InterfaceDeclarations) { 1143 verifyFormat("interface I {\n" 1144 " x: string;\n" 1145 " enum: string[];\n" 1146 " enum?: string[];\n" 1147 "}\n" 1148 "var y;"); 1149 // Ensure that state is reset after parsing the interface. 1150 verifyFormat("interface a {}\n" 1151 "export function b() {}\n" 1152 "var x;"); 1153 1154 // Arrays of object type literals. 1155 verifyFormat("interface I {\n" 1156 " o: {}[];\n" 1157 "}"); 1158 } 1159 1160 TEST_F(FormatTestJS, EnumDeclarations) { 1161 verifyFormat("enum Foo {\n" 1162 " A = 1,\n" 1163 " B\n" 1164 "}"); 1165 verifyFormat("export /* somecomment*/ enum Foo {\n" 1166 " A = 1,\n" 1167 " B\n" 1168 "}"); 1169 verifyFormat("enum Foo {\n" 1170 " A = 1, // comment\n" 1171 " B\n" 1172 "}\n" 1173 "var x = 1;"); 1174 } 1175 1176 TEST_F(FormatTestJS, MetadataAnnotations) { 1177 verifyFormat("@A\nclass C {\n}"); 1178 verifyFormat("@A({arg: 'value'})\nclass C {\n}"); 1179 verifyFormat("@A\n@B\nclass C {\n}"); 1180 verifyFormat("class C {\n @A x: string;\n}"); 1181 verifyFormat("class C {\n" 1182 " @A\n" 1183 " private x(): string {\n" 1184 " return 'y';\n" 1185 " }\n" 1186 "}"); 1187 verifyFormat("class C {\n" 1188 " private x(@A x: string) {}\n" 1189 "}"); 1190 verifyFormat("class X {}\n" 1191 "class Y {}"); 1192 } 1193 1194 TEST_F(FormatTestJS, TypeAliases) { 1195 verifyFormat("type X = number;\n" 1196 "class C {}"); 1197 verifyFormat("type X<Y> = Z<Y>;"); 1198 verifyFormat("type X = {\n" 1199 " y: number\n" 1200 "};\n" 1201 "class C {}"); 1202 } 1203 1204 TEST_F(FormatTestJS, Modules) { 1205 verifyFormat("import SomeThing from 'some/module.js';"); 1206 verifyFormat("import {X, Y} from 'some/module.js';"); 1207 verifyFormat("import a, {X, Y} from 'some/module.js';"); 1208 verifyFormat("import {X, Y,} from 'some/module.js';"); 1209 verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';"); 1210 // Ensure Automatic Semicolon Insertion does not break on "as\n". 1211 verifyFormat("import {X as myX} from 'm';", "import {X as\n" 1212 " myX} from 'm';"); 1213 verifyFormat("import * as lib from 'some/module.js';"); 1214 verifyFormat("var x = {import: 1};\nx.import = 2;"); 1215 1216 verifyFormat("export function fn() {\n" 1217 " return 'fn';\n" 1218 "}"); 1219 verifyFormat("export function A() {}\n" 1220 "export default function B() {}\n" 1221 "export function C() {}"); 1222 verifyFormat("export default () => {\n" 1223 " let x = 1;\n" 1224 " return x;\n" 1225 "}"); 1226 verifyFormat("export const x = 12;"); 1227 verifyFormat("export default class X {}"); 1228 verifyFormat("export {X, Y} from 'some/module.js';"); 1229 verifyFormat("export {X, Y,} from 'some/module.js';"); 1230 verifyFormat("export {SomeVeryLongExport as X, " 1231 "SomeOtherVeryLongExport as Y} from 'some/module.js';"); 1232 // export without 'from' is wrapped. 1233 verifyFormat("export let someRatherLongVariableName =\n" 1234 " someSurprisinglyLongVariable + someOtherRatherLongVar;"); 1235 // ... but not if from is just an identifier. 1236 verifyFormat("export {\n" 1237 " from as from,\n" 1238 " someSurprisinglyLongVariable as\n" 1239 " from\n" 1240 "};", 1241 getGoogleJSStyleWithColumns(20)); 1242 verifyFormat("export class C {\n" 1243 " x: number;\n" 1244 " y: string;\n" 1245 "}"); 1246 verifyFormat("export class X { y: number; }"); 1247 verifyFormat("export abstract class X { y: number; }"); 1248 verifyFormat("export default class X { y: number }"); 1249 verifyFormat("export default function() {\n return 1;\n}"); 1250 verifyFormat("export var x = 12;"); 1251 verifyFormat("class C {}\n" 1252 "export function f() {}\n" 1253 "var v;"); 1254 verifyFormat("export var x: number = 12;"); 1255 verifyFormat("export const y = {\n" 1256 " a: 1,\n" 1257 " b: 2\n" 1258 "};"); 1259 verifyFormat("export enum Foo {\n" 1260 " BAR,\n" 1261 " // adsdasd\n" 1262 " BAZ\n" 1263 "}"); 1264 verifyFormat("export default [\n" 1265 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 1266 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 1267 "];"); 1268 verifyFormat("export default [];"); 1269 verifyFormat("export default () => {};"); 1270 verifyFormat("export interface Foo { foo: number; }\n" 1271 "export class Bar {\n" 1272 " blah(): string {\n" 1273 " return this.blah;\n" 1274 " };\n" 1275 "}"); 1276 } 1277 1278 TEST_F(FormatTestJS, ImportWrapping) { 1279 verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying," 1280 " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying" 1281 "} from 'some/module.js';"); 1282 FormatStyle Style = getGoogleJSStyleWithColumns(80); 1283 Style.JavaScriptWrapImports = true; 1284 verifyFormat("import {\n" 1285 " VeryLongImportsAreAnnoying,\n" 1286 " VeryLongImportsAreAnnoying,\n" 1287 " VeryLongImportsAreAnnoying,\n" 1288 "} from 'some/module.js';", 1289 Style); 1290 verifyFormat("import {\n" 1291 " A,\n" 1292 " A,\n" 1293 "} from 'some/module.js';", 1294 Style); 1295 verifyFormat("export {\n" 1296 " A,\n" 1297 " A,\n" 1298 "} from 'some/module.js';", 1299 Style); 1300 } 1301 1302 TEST_F(FormatTestJS, TemplateStrings) { 1303 // Keeps any whitespace/indentation within the template string. 1304 verifyFormat("var x = `hello\n" 1305 " ${name}\n" 1306 " !`;", 1307 "var x = `hello\n" 1308 " ${ name }\n" 1309 " !`;"); 1310 1311 verifyFormat("var x =\n" 1312 " `hello ${world}` >= some();", 1313 getGoogleJSStyleWithColumns(34)); // Barely doesn't fit. 1314 verifyFormat("var x = `hello ${world}` >= some();", 1315 getGoogleJSStyleWithColumns(35)); // Barely fits. 1316 verifyFormat("var x = `hellö ${wörld}` >= söme();", 1317 getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8. 1318 verifyFormat("var x = `hello\n" 1319 " ${world}` >=\n" 1320 " some();", 1321 "var x =\n" 1322 " `hello\n" 1323 " ${world}` >= some();", 1324 getGoogleJSStyleWithColumns(21)); // Barely doesn't fit. 1325 verifyFormat("var x = `hello\n" 1326 " ${world}` >= some();", 1327 "var x =\n" 1328 " `hello\n" 1329 " ${world}` >= some();", 1330 getGoogleJSStyleWithColumns(22)); // Barely fits. 1331 1332 verifyFormat("var x =\n" 1333 " `h`;", 1334 getGoogleJSStyleWithColumns(11)); 1335 verifyFormat("var x =\n `multi\n line`;", "var x = `multi\n line`;", 1336 getGoogleJSStyleWithColumns(13)); 1337 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1338 " `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);"); 1339 // Repro for an obscure width-miscounting issue with template strings. 1340 verifyFormat( 1341 "someLongVariable =\n" 1342 " " 1343 "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;", 1344 "someLongVariable = " 1345 "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;"); 1346 1347 // Make sure template strings get a proper ColumnWidth assigned, even if they 1348 // are first token in line. 1349 verifyFormat( 1350 "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 1351 " `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;"); 1352 1353 // Two template strings. 1354 verifyFormat("var x = `hello` == `hello`;"); 1355 1356 // Comments in template strings. 1357 verifyFormat("var x = `//a`;\n" 1358 "var y;", 1359 "var x =\n `//a`;\n" 1360 "var y ;"); 1361 verifyFormat("var x = `/*a`;\n" 1362 "var y;", 1363 "var x =\n `/*a`;\n" 1364 "var y;"); 1365 // Unterminated string literals in a template string. 1366 verifyFormat("var x = `'`; // comment with matching quote '\n" 1367 "var y;"); 1368 verifyFormat("var x = `\"`; // comment with matching quote \"\n" 1369 "var y;"); 1370 verifyFormat("it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa);", 1371 "it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa) ;", 1372 getGoogleJSStyleWithColumns(40)); 1373 // Backticks in a comment - not a template string. 1374 verifyFormat("var x = 1 // `/*a`;\n" 1375 " ;", 1376 "var x =\n 1 // `/*a`;\n" 1377 " ;"); 1378 verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */"); 1379 // Comment spans multiple template strings. 1380 verifyFormat("var x = `/*a`;\n" 1381 "var y = ` */ `;", 1382 "var x =\n `/*a`;\n" 1383 "var y =\n ` */ `;"); 1384 // Escaped backtick. 1385 verifyFormat("var x = ` \\` a`;\n" 1386 "var y;", 1387 "var x = ` \\` a`;\n" 1388 "var y;"); 1389 // Escaped dollar. 1390 verifyFormat("var x = ` \\${foo}`;\n"); 1391 1392 // The token stream can contain two string_literals in sequence, but that 1393 // doesn't mean that they are implicitly concatenated in JavaScript. 1394 verifyFormat("var f = `aaaa ${a ? 'a' : 'b'}`;"); 1395 1396 // Ensure that scopes are appropriately set around evaluated expressions in 1397 // template strings. 1398 verifyFormat("var f = `aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa\n" 1399 " aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`;", 1400 "var f = `aaaaaaaaaaaaa:${aaaaaaa. aaaaa} aaaaaaaa\n" 1401 " aaaaaaaaaaaaa:${ aaaaaaa. aaaaa} aaaaaaaa`;"); 1402 } 1403 1404 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) { 1405 verifyFormat("var f = `aaaaaaaaaaaaaaaaaa: ${aaaaa + //\n" 1406 " bbbb}`;", 1407 "var f = `aaaaaaaaaaaaaaaaaa: ${aaaaa + //\n" 1408 " bbbb}`;"); 1409 verifyFormat("var f = `aaaaaaaaaaaaaaaaaa: ${ //\n" 1410 " aaaaa + //\n" 1411 " bbbb}`;", 1412 "var f = `aaaaaaaaaaaaaaaaaa: ${ //\n" 1413 " aaaaa + //\n" 1414 " bbbb}`;"); 1415 verifyFormat("var f = `\n" 1416 " aaaaaaaaaaaaaaaaaa: ${aaaaa + //\n" 1417 " bbbb}`;", 1418 "var f = `\n" 1419 " aaaaaaaaaaaaaaaaaa: ${ aaaaa + //\n" 1420 " bbbb }`;"); 1421 verifyFormat("var f = `\n" 1422 " aaaaaaaaaaaaaaaaaa: ${ //\n" 1423 " aaaaa + //\n" 1424 " bbbb}`;", 1425 "var f = `\n" 1426 " aaaaaaaaaaaaaaaaaa: ${ //\n" 1427 " aaaaa + //\n" 1428 " bbbb}` ;"); 1429 verifyFormat("var f = `\n" 1430 " aaaaaaaaaaaaaaaaaa: ${someFunction(\n" 1431 " aaaaa + //\n" 1432 " bbbb)}`;", 1433 "var f = `\n" 1434 " aaaaaaaaaaaaaaaaaa: ${ someFunction (\n" 1435 " aaaaa + //\n" 1436 " bbbb)}`;"); 1437 verifyFormat("var f = `\n" 1438 " aaaaaaaaaaaaaaaaaa: ${ //\n" 1439 " someFunction(\n" 1440 " aaaaa + //\n" 1441 " bbbb)}`;", 1442 "var f = `\n" 1443 " aaaaaaaaaaaaaaaaaa: ${ //\n" 1444 " someFunction (\n" 1445 " aaaaa + //\n" 1446 " bbbb)}`;"); 1447 verifyFormat("var f = `\n" 1448 " aaaaaaaaaaaaaaaaaa: ${ //\n" 1449 " someFunction({\n" 1450 " aaaa: aaaaa,\n" 1451 " bbbb: bbbbb,\n" 1452 " })}`;", 1453 "var f = `\n" 1454 " aaaaaaaaaaaaaaaaaa: ${ //\n" 1455 " someFunction ({\n" 1456 " aaaa: aaaaa,\n" 1457 " bbbb: bbbbb,\n" 1458 " })}`;"); 1459 } 1460 1461 TEST_F(FormatTestJS, TemplateStringASI) { 1462 verifyFormat("var x = `hello${world}`;", "var x = `hello${\n" 1463 " world\n" 1464 "}`;"); 1465 } 1466 1467 TEST_F(FormatTestJS, NestedTemplateStrings) { 1468 verifyFormat( 1469 "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;"); 1470 verifyFormat("var x = `he${({text: 'll'}.text)}o`;"); 1471 1472 // Crashed at some point. 1473 verifyFormat("}"); 1474 } 1475 1476 TEST_F(FormatTestJS, TaggedTemplateStrings) { 1477 verifyFormat("var x = html`<ul>`;"); 1478 } 1479 1480 TEST_F(FormatTestJS, CastSyntax) { 1481 verifyFormat("var x = <type>foo;"); 1482 verifyFormat("var x = foo as type;"); 1483 verifyFormat("let x = (a + b) as\n" 1484 " LongTypeIsLong;", 1485 getGoogleJSStyleWithColumns(20)); 1486 verifyFormat("foo = <Bar[]>[\n" 1487 " 1, //\n" 1488 " 2\n" 1489 "];"); 1490 verifyFormat("var x = [{x: 1} as type];"); 1491 verifyFormat("x = x as [a, b];"); 1492 verifyFormat("x = x as {a: string};"); 1493 verifyFormat("x = x as (string);"); 1494 verifyFormat("x = x! as (string);"); 1495 } 1496 1497 TEST_F(FormatTestJS, TypeArguments) { 1498 verifyFormat("class X<Y> {}"); 1499 verifyFormat("new X<Y>();"); 1500 verifyFormat("foo<Y>(a);"); 1501 verifyFormat("var x: X<Y>[];"); 1502 verifyFormat("class C extends D<E> implements F<G>, H<I> {}"); 1503 verifyFormat("function f(a: List<any> = null) {}"); 1504 verifyFormat("function f(): List<any> {}"); 1505 verifyFormat("function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():\n" 1506 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}"); 1507 verifyFormat("function aaaaaaaaaa(\n" 1508 " aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa,\n" 1509 " aaaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaa):\n" 1510 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}"); 1511 } 1512 1513 TEST_F(FormatTestJS, UserDefinedTypeGuards) { 1514 verifyFormat( 1515 "function foo(check: Object):\n" 1516 " check is {foo: string, bar: string, baz: string, foobar: string} {\n" 1517 " return 'bar' in check;\n" 1518 "}\n"); 1519 } 1520 1521 TEST_F(FormatTestJS, OptionalTypes) { 1522 verifyFormat("function x(a?: b, c?, d?) {}"); 1523 verifyFormat("class X {\n" 1524 " y?: z;\n" 1525 " z?;\n" 1526 "}"); 1527 verifyFormat("interface X {\n" 1528 " y?(): z;\n" 1529 "}"); 1530 verifyFormat("constructor({aa}: {\n" 1531 " aa?: string,\n" 1532 " aaaaaaaa?: string,\n" 1533 " aaaaaaaaaaaaaaa?: boolean,\n" 1534 " aaaaaa?: List<string>\n" 1535 "}) {}"); 1536 } 1537 1538 TEST_F(FormatTestJS, IndexSignature) { 1539 verifyFormat("var x: {[k: string]: v};"); 1540 } 1541 1542 TEST_F(FormatTestJS, WrapAfterParen) { 1543 verifyFormat("xxxxxxxxxxx(\n" 1544 " aaa, aaa);", 1545 getGoogleJSStyleWithColumns(20)); 1546 verifyFormat("xxxxxxxxxxx(\n" 1547 " aaa, aaa, aaa,\n" 1548 " aaa, aaa, aaa);", 1549 getGoogleJSStyleWithColumns(20)); 1550 verifyFormat("xxxxxxxxxxx(\n" 1551 " aaaaaaaaaaaaaaaaaaaaaaaa,\n" 1552 " function(x) {\n" 1553 " y(); //\n" 1554 " });", 1555 getGoogleJSStyleWithColumns(40)); 1556 verifyFormat("while (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 1557 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 1558 } 1559 1560 TEST_F(FormatTestJS, JSDocAnnotations) { 1561 verifyFormat("/**\n" 1562 " * @export {this.is.a.long.path.to.a.Type}\n" 1563 " */", 1564 "/**\n" 1565 " * @export {this.is.a.long.path.to.a.Type}\n" 1566 " */", 1567 getGoogleJSStyleWithColumns(20)); 1568 } 1569 1570 TEST_F(FormatTestJS, RequoteStringsSingle) { 1571 verifyFormat("var x = 'foo';", "var x = \"foo\";"); 1572 verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";"); 1573 verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";"); 1574 verifyFormat( 1575 "var x =\n" 1576 " 'foo\\'';", 1577 // Code below is 15 chars wide, doesn't fit into the line with the 1578 // \ escape added. 1579 "var x = \"foo'\";", getGoogleJSStyleWithColumns(15)); 1580 // Removes no-longer needed \ escape from ". 1581 verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";"); 1582 // Code below fits into 15 chars *after* removing the \ escape. 1583 verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";", 1584 getGoogleJSStyleWithColumns(15)); 1585 verifyFormat("// clang-format off\n" 1586 "let x = \"double\";\n" 1587 "// clang-format on\n" 1588 "let x = 'single';\n", 1589 "// clang-format off\n" 1590 "let x = \"double\";\n" 1591 "// clang-format on\n" 1592 "let x = \"single\";\n"); 1593 } 1594 1595 TEST_F(FormatTestJS, RequoteAndIndent) { 1596 verifyFormat("let x = someVeryLongFunctionThatGoesOnAndOn(\n" 1597 " 'double quoted string that needs wrapping');", 1598 "let x = someVeryLongFunctionThatGoesOnAndOn(" 1599 "\"double quoted string that needs wrapping\");"); 1600 1601 verifyFormat("let x =\n" 1602 " 'foo\\'oo';\n" 1603 "let x =\n" 1604 " 'foo\\'oo';", 1605 "let x=\"foo'oo\";\n" 1606 "let x=\"foo'oo\";", 1607 getGoogleJSStyleWithColumns(15)); 1608 } 1609 1610 TEST_F(FormatTestJS, RequoteStringsDouble) { 1611 FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript); 1612 DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double; 1613 verifyFormat("var x = \"foo\";", DoubleQuotes); 1614 verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes); 1615 verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes); 1616 } 1617 1618 TEST_F(FormatTestJS, RequoteStringsLeave) { 1619 FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript); 1620 LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave; 1621 verifyFormat("var x = \"foo\";", LeaveQuotes); 1622 verifyFormat("var x = 'foo';", LeaveQuotes); 1623 } 1624 1625 TEST_F(FormatTestJS, SupportShebangLines) { 1626 verifyFormat("#!/usr/bin/env node\n" 1627 "var x = hello();", 1628 "#!/usr/bin/env node\n" 1629 "var x = hello();"); 1630 } 1631 1632 TEST_F(FormatTestJS, NonNullAssertionOperator) { 1633 verifyFormat("let x = foo!.bar();\n"); 1634 verifyFormat("let x = foo ? bar! : baz;\n"); 1635 verifyFormat("let x = !foo;\n"); 1636 verifyFormat("let x = foo[0]!;\n"); 1637 verifyFormat("let x = (foo)!;\n"); 1638 verifyFormat("let x = foo! - 1;\n"); 1639 verifyFormat("let x = {foo: 1}!;\n"); 1640 } 1641 1642 TEST_F(FormatTestJS, Conditional) { 1643 verifyFormat("y = x ? 1 : 2;"); 1644 verifyFormat("x ? 1 : 2;"); 1645 verifyFormat("class Foo {\n" 1646 " field = true ? 1 : 2;\n" 1647 " method(a = true ? 1 : 2) {}\n" 1648 "}"); 1649 } 1650 1651 TEST_F(FormatTestJS, ImportComments) { 1652 verifyFormat("import {x} from 'x'; // from some location", 1653 getGoogleJSStyleWithColumns(25)); 1654 verifyFormat("// taze: x from 'location'", getGoogleJSStyleWithColumns(10)); 1655 } 1656 1657 } // end namespace tooling 1658 } // end namespace clang 1659