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