1 //===- unittest/Format/FormatTestJS.cpp - Formatting unit tests for JS ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "FormatTestUtils.h"
11 #include "clang/Format/Format.h"
12 #include "llvm/Support/Debug.h"
13 #include "gtest/gtest.h"
15 #define DEBUG_TYPE "format-test"
20 class FormatTestJS : public ::testing::Test {
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 tooling::Replacements Replaces = reformat(Style, Code, Ranges);
28 std::string Result = applyAllReplacements(Code, Replaces);
29 EXPECT_NE("", Result);
30 DEBUG(llvm::errs() << "\n" << Result << "\n\n");
34 static std::string format(
36 const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
37 return format(Code, 0, Code.size(), Style);
40 static FormatStyle getGoogleJSStyleWithColumns(unsigned ColumnLimit) {
41 FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
42 Style.ColumnLimit = ColumnLimit;
46 static void verifyFormat(
48 const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
49 EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
53 TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
54 verifyFormat("a == = b;");
55 verifyFormat("a != = b;");
57 verifyFormat("a === b;");
58 verifyFormat("aaaaaaa ===\n b;", getGoogleJSStyleWithColumns(10));
59 verifyFormat("a !== b;");
60 verifyFormat("aaaaaaa !==\n b;", getGoogleJSStyleWithColumns(10));
61 verifyFormat("if (a + b + c +\n"
65 getGoogleJSStyleWithColumns(20));
67 verifyFormat("a >> >= b;");
69 verifyFormat("a >>> b;");
70 verifyFormat("aaaaaaa >>>\n b;", getGoogleJSStyleWithColumns(10));
71 verifyFormat("a >>>= b;");
72 verifyFormat("aaaaaaa >>>=\n b;", getGoogleJSStyleWithColumns(10));
73 verifyFormat("if (a + b + c +\n"
77 getGoogleJSStyleWithColumns(20));
78 verifyFormat("var x = aaaaaaaaaa ?\n"
81 getGoogleJSStyleWithColumns(20));
83 verifyFormat("var b = a.map((x) => x + 1);");
84 verifyFormat("return ('aaa') in bbbb;");
86 // ES6 spread operator.
87 verifyFormat("someFunction(...a);");
88 verifyFormat("var x = [1, ...a, 2];");
91 TEST_F(FormatTestJS, UnderstandsAmpAmp) {
92 verifyFormat("e && e.SomeFunction();");
95 TEST_F(FormatTestJS, LiteralOperatorsCanBeKeywords) {
96 verifyFormat("not.and.or.not_eq = 1;");
99 TEST_F(FormatTestJS, ES6DestructuringAssignment) {
100 verifyFormat("var [a, b, c] = [1, 2, 3];");
101 verifyFormat("var {a, b} = {a: 1, b: 2};");
104 TEST_F(FormatTestJS, ContainerLiterals) {
105 verifyFormat("var x = {y: function(a) { return a; }};");
106 verifyFormat("return {\n"
107 " link: function() {\n"
111 verifyFormat("return {\n"
113 " link: function() {\n"
117 verifyFormat("return {\n"
119 " link: function() {\n"
122 " link: function() {\n"
126 verifyFormat("var stuff = {\n"
127 " // comment for update\n"
129 " // comment for modules\n"
131 " // comment for tasks\n"
134 verifyFormat("return {\n"
139 verifyFormat("var obj = {\n"
140 " fooooooooo: function(x) {\n"
141 " return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
144 // Simple object literal, as opposed to enum style below.
145 verifyFormat("var obj = {a: 123};");
146 // Enum style top level assignment.
147 verifyFormat("X = {\n a: 123\n};");
148 verifyFormat("X.Y = {\n a: 123\n};");
149 verifyFormat("x = foo && {a: 123};");
151 // Arrow functions in object literals.
152 verifyFormat("var x = {y: (a) => { return a; }};");
153 verifyFormat("var x = {y: (a) => a};");
156 TEST_F(FormatTestJS, MethodsInObjectLiterals) {
157 verifyFormat("var o = {\n"
159 " get value() { // getter\n"
160 " return this.value;\n"
163 verifyFormat("var o = {\n"
165 " set value(val) { // setter\n"
166 " this.value = val;\n"
169 verifyFormat("var o = {\n"
171 " someMethod(val) { // method\n"
172 " doSomething(this.value + val);\n"
175 verifyFormat("var o = {\n"
176 " someMethod(val) { // method\n"
177 " doSomething(this.value + val);\n"
179 " someOtherMethod(val) { // method\n"
180 " doSomething(this.value + val);\n"
185 TEST_F(FormatTestJS, SpacesInContainerLiterals) {
186 verifyFormat("var arr = [1, 2, 3];");
187 verifyFormat("f({a: 1, b: 2, c: 3});");
189 verifyFormat("var object_literal_with_long_name = {\n"
190 " a: 'aaaaaaaaaaaaaaaaaa',\n"
191 " b: 'bbbbbbbbbbbbbbbbbb'\n"
194 verifyFormat("f({a: 1, b: 2, c: 3});",
195 getChromiumStyle(FormatStyle::LK_JavaScript));
196 verifyFormat("f({'a': [{}]});");
199 TEST_F(FormatTestJS, SingleQuoteStrings) {
200 verifyFormat("this.function('', true);");
203 TEST_F(FormatTestJS, GoogScopes) {
204 verifyFormat("goog.scope(function() {\n"
207 "}); // goog.scope");
208 verifyFormat("goog.scope(function() {\n"
215 TEST_F(FormatTestJS, GoogModules) {
216 verifyFormat("goog.module('this.is.really.absurdly.long');",
217 getGoogleJSStyleWithColumns(40));
218 verifyFormat("goog.require('this.is.really.absurdly.long');",
219 getGoogleJSStyleWithColumns(40));
220 verifyFormat("goog.provide('this.is.really.absurdly.long');",
221 getGoogleJSStyleWithColumns(40));
222 verifyFormat("var long = goog.require('this.is.really.absurdly.long');",
223 getGoogleJSStyleWithColumns(40));
225 // These should be wrapped normally.
227 "var MyLongClassName =\n"
228 " goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
231 TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
232 verifyFormat("function outer1(a, b) {\n"
233 " function inner1(a, b) { return a; }\n"
236 "function outer2(a, b) {\n"
237 " function inner2(a, b) { return a; }\n"
242 TEST_F(FormatTestJS, FunctionLiterals) {
243 verifyFormat("doFoo(function() {});");
244 verifyFormat("doFoo(function() { return 1; });");
245 verifyFormat("var func = function() {\n"
248 verifyFormat("return {\n"
250 " setAttribute: function(key, val) { this[key] = val; },\n"
251 " getAttribute: function(key) { return this[key]; },\n"
252 " style: {direction: ''}\n"
255 EXPECT_EQ("abc = xyz ?\n"
262 format("abc=xyz?function(){return 1;}:function(){return -1;};"));
264 verifyFormat("var closure = goog.bind(\n"
265 " function() { // comment\n"
269 " this, arg1IsReallyLongAndNeeedsLineBreaks,\n"
270 " arg3IsReallyLongAndNeeedsLineBreaks);");
271 verifyFormat("var closure = goog.bind(function() { // comment\n"
275 verifyFormat("return {\n"
278 " return function() {\n"
284 " var someVariable = function(x) {\n"
285 " return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
288 verifyFormat("someLooooooooongFunction(\n"
289 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
290 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
291 " function(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
295 verifyFormat("f({a: function() { return 1; }});",
296 getGoogleJSStyleWithColumns(33));
298 " a: function() { return 1; }\n"
300 getGoogleJSStyleWithColumns(32));
302 verifyFormat("return {\n"
303 " a: function SomeFunction() {\n"
308 verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
309 " .then(goog.bind(function(aaaaaaaaaaa) {\n"
312 " }, this), aaaaaaaaaaaaaaaaa);");
314 // FIXME: This is not ideal yet.
315 verifyFormat("someFunction(goog.bind(\n"
321 " goog.bind(function() {\n"
327 TEST_F(FormatTestJS, InliningFunctionLiterals) {
328 FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
329 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
330 verifyFormat("var func = function() {\n"
334 verifyFormat("var func = doSomething(function() { return 1; });", Style);
335 verifyFormat("var outer = function() {\n"
336 " var inner = function() { return 1; }\n"
339 verifyFormat("function outer1(a, b) {\n"
340 " function inner1(a, b) { return a; }\n"
344 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
345 verifyFormat("var func = function() { return 1; };", Style);
346 verifyFormat("var func = doSomething(function() { return 1; });", Style);
348 "var outer = function() { var inner = function() { return 1; } };",
350 verifyFormat("function outer1(a, b) {\n"
351 " function inner1(a, b) { return a; }\n"
355 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
356 verifyFormat("var func = function() {\n"
360 verifyFormat("var func = doSomething(function() {\n"
364 verifyFormat("var outer = function() {\n"
365 " var inner = function() {\n"
370 verifyFormat("function outer1(a, b) {\n"
371 " function inner1(a, b) {\n"
378 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
379 verifyFormat("promise.then(\n"
380 " function success() {\n"
384 " function error() {\n"
389 verifyFormat("promise.then(\n"
390 " function success() {\n"
395 " function error() {\n"
399 // FIXME: Here, we should probably break right after the "(" for consistency.
400 verifyFormat("promise.then([],\n"
401 " function success() {\n"
405 " function error() {\n"
410 verifyFormat("getSomeLongPromise()\n"
411 " .then(function(value) { body(); })\n"
412 " .thenCatch(function(error) {\n"
416 verifyFormat("getSomeLongPromise()\n"
417 " .then(function(value) {\n"
421 " .thenCatch(function(error) {\n"
426 verifyFormat("getSomeLongPromise()\n"
427 " .then(function(value) { body(); })\n"
428 " .thenCatch(function(error) { body(); });");
431 TEST_F(FormatTestJS, ArrowFunctions) {
432 verifyFormat("var x = (a) => {\n"
435 verifyFormat("var x = (a) => {\n"
436 " function y() { return 42; }\n"
439 verifyFormat("var x = (a: type): {some: type} => {\n"
442 verifyFormat("var x = (a) => a;");
443 verifyFormat("var x = (a) => a;");
446 TEST_F(FormatTestJS, ReturnStatements) {
447 verifyFormat("function() {\n"
448 " return [hello, world];\n"
452 TEST_F(FormatTestJS, ClosureStyleCasts) {
453 verifyFormat("var x = /** @type {foo} */ (bar);");
456 TEST_F(FormatTestJS, TryCatch) {
457 verifyFormat("try {\n"
465 // But, of course, "catch" is a perfectly fine function name in JavaScript.
466 verifyFormat("someObject.catch();");
467 verifyFormat("someObject.new();");
468 verifyFormat("someObject.delete();");
471 TEST_F(FormatTestJS, StringLiteralConcatenation) {
472 verifyFormat("var literal = 'hello ' +\n"
476 TEST_F(FormatTestJS, RegexLiteralClassification) {
478 verifyFormat("var regex = /abc/;");
479 verifyFormat("f(/abc/);");
480 verifyFormat("f(abc, /abc/);");
481 verifyFormat("some_map[/abc/];");
482 verifyFormat("var x = a ? /abc/ : /abc/;");
483 verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
484 verifyFormat("var x = !/abc/.test(y);");
485 verifyFormat("var x = a && /abc/.test(y);");
486 verifyFormat("var x = a || /abc/.test(y);");
487 verifyFormat("var x = a + /abc/.search(y);");
488 verifyFormat("var regexs = {/abc/, /abc/};");
489 verifyFormat("return /abc/;");
491 // Not regex literals.
492 verifyFormat("var a = a / 2 + b / 3;");
495 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
496 verifyFormat("var regex = /=/;");
497 verifyFormat("var regex = /a*/;");
498 verifyFormat("var regex = /a+/;");
499 verifyFormat("var regex = /a?/;");
500 verifyFormat("var regex = /.a./;");
501 verifyFormat("var regex = /a\\*/;");
502 verifyFormat("var regex = /^a$/;");
503 verifyFormat("var regex = /\\/a/;");
504 verifyFormat("var regex = /(?:x)/;");
505 verifyFormat("var regex = /x(?=y)/;");
506 verifyFormat("var regex = /x(?!y)/;");
507 verifyFormat("var regex = /x|y/;");
508 verifyFormat("var regex = /a{2}/;");
509 verifyFormat("var regex = /a{1,3}/;");
510 verifyFormat("var regex = /[abc]/;");
511 verifyFormat("var regex = /[^abc]/;");
512 verifyFormat("var regex = /[\\b]/;");
513 verifyFormat("var regex = /\\b/;");
514 verifyFormat("var regex = /\\B/;");
515 verifyFormat("var regex = /\\d/;");
516 verifyFormat("var regex = /\\D/;");
517 verifyFormat("var regex = /\\f/;");
518 verifyFormat("var regex = /\\n/;");
519 verifyFormat("var regex = /\\r/;");
520 verifyFormat("var regex = /\\s/;");
521 verifyFormat("var regex = /\\S/;");
522 verifyFormat("var regex = /\\t/;");
523 verifyFormat("var regex = /\\v/;");
524 verifyFormat("var regex = /\\w/;");
525 verifyFormat("var regex = /\\W/;");
526 verifyFormat("var regex = /a(a)\\1/;");
527 verifyFormat("var regex = /\\0/;");
528 verifyFormat("var regex = /\\\\/g;");
529 verifyFormat("var regex = /\\a\\\\/g;");
530 verifyFormat("var regex = /\a\\//g;");
531 verifyFormat("var regex = /a\\//;\n"
533 EXPECT_EQ("var regex = /\\/*/;\n"
535 format("var regex = /\\/*/;\n"
539 TEST_F(FormatTestJS, RegexLiteralModifiers) {
540 verifyFormat("var regex = /abc/g;");
541 verifyFormat("var regex = /abc/i;");
542 verifyFormat("var regex = /abc/m;");
543 verifyFormat("var regex = /abc/y;");
546 TEST_F(FormatTestJS, RegexLiteralLength) {
547 verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
548 getGoogleJSStyleWithColumns(60));
549 verifyFormat("var regex =\n"
550 " /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
551 getGoogleJSStyleWithColumns(60));
552 verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
553 getGoogleJSStyleWithColumns(50));
556 TEST_F(FormatTestJS, RegexLiteralExamples) {
557 verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
560 TEST_F(FormatTestJS, TypeAnnotations) {
561 verifyFormat("var x: string;");
562 verifyFormat("function x(): string {\n return 'x';\n}");
563 verifyFormat("function x(): {x: string} {\n return {x: 'x'};\n}");
564 verifyFormat("function x(y: string): string {\n return 'x';\n}");
565 verifyFormat("for (var y: string in x) {\n x();\n}");
566 verifyFormat("((a: string, b: number): string => a + b);");
567 verifyFormat("var x: (y: number) => string;");
568 verifyFormat("var x: P<string, (a: number) => string>;");
569 verifyFormat("var x = {y: function(): z { return 1; }};");
570 verifyFormat("var x = {y: function(): {a: number} { return 1; }};");
573 TEST_F(FormatTestJS, ClassDeclarations) {
574 verifyFormat("class C {\n x: string = 12;\n}");
575 verifyFormat("class C {\n x(): string => 12;\n}");
576 verifyFormat("class C {\n ['x' + 2]: string = 12;\n}");
577 verifyFormat("class C {\n private x: string = 12;\n}");
578 verifyFormat("class C {\n private static x: string = 12;\n}");
579 verifyFormat("class C {\n static x(): string { return 'asd'; }\n}");
580 verifyFormat("class C extends P implements I {}");
581 verifyFormat("class C extends p.P implements i.I {}");
584 TEST_F(FormatTestJS, InterfaceDeclarations) {
585 verifyFormat("interface I {\n"
590 TEST_F(FormatTestJS, MetadataAnnotations) {
591 verifyFormat("@A\nclass C {\n}");
592 verifyFormat("@A({arg: 'value'})\nclass C {\n}");
593 verifyFormat("@A\n@B\nclass C {\n}");
594 verifyFormat("class C {\n @A x: string;\n}");
595 verifyFormat("class C {\n"
597 " private x(): string {\n"
601 verifyFormat("class X {}\n"
605 TEST_F(FormatTestJS, Modules) {
606 verifyFormat("import SomeThing from 'some/module.js';");
607 verifyFormat("import {X, Y} from 'some/module.js';");
608 verifyFormat("import {\n"
609 " VeryLongImportsAreAnnoying,\n"
610 " VeryLongImportsAreAnnoying,\n"
611 " VeryLongImportsAreAnnoying,\n"
612 " VeryLongImportsAreAnnoying\n"
613 "} from 'some/module.js';");
614 verifyFormat("import {\n"
617 "} from 'some/module.js';");
618 verifyFormat("import {\n"
621 "} from 'some/long/module.js';",
622 getGoogleJSStyleWithColumns(20));
623 verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
624 verifyFormat("import * as lib from 'some/module.js';");
625 verifyFormat("var x = {import: 1};\nx.import = 2;");
627 verifyFormat("export function fn() {\n"
630 verifyFormat("export function A() {\n"
632 "export default function B() {\n"
634 "export function C() {\n"
636 verifyFormat("export const x = 12;");
637 verifyFormat("export default class X {}");
638 verifyFormat("export {X, Y} from 'some/module.js';");
639 verifyFormat("export {\n"
642 "} from 'some/module.js';");
643 verifyFormat("export class C {\n"
647 verifyFormat("export class X { y: number; }");
648 verifyFormat("export default class X { y: number }");
649 verifyFormat("export default function() {\n return 1;\n}");
650 verifyFormat("export var x = 12;");
651 verifyFormat("export var x: number = 12;");
652 verifyFormat("export const y = {\n"
658 TEST_F(FormatTestJS, TemplateStrings) {
659 // Keeps any whitespace/indentation within the template string.
660 EXPECT_EQ("var x = `hello\n"
663 format("var x = `hello\n"
667 // FIXME: +1 / -1 offsets are to work around clang-format miscalculating
668 // widths for unknown tokens that are not whitespace (e.g. '`'). Remove when
669 // the code is corrected.
671 verifyFormat("var x =\n"
672 " `hello ${world}` >= some();",
673 getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
674 verifyFormat("var x = `hello ${world}` >= some();",
675 getGoogleJSStyleWithColumns(35 + 1)); // Barely fits.
676 EXPECT_EQ("var x = `hello\n"
681 " ${world}` >= some();",
682 getGoogleJSStyleWithColumns(21))); // Barely doesn't fit.
683 EXPECT_EQ("var x = `hello\n"
684 " ${world}` >= some();",
687 " ${world}` >= some();",
688 getGoogleJSStyleWithColumns(22))); // Barely fits.
690 verifyFormat("var x =\n `h`;", getGoogleJSStyleWithColumns(13 - 1));
692 "var x =\n `multi\n line`;",
693 format("var x = `multi\n line`;", getGoogleJSStyleWithColumns(14 - 1)));
695 // Make sure template strings get a proper ColumnWidth assigned, even if they
696 // are first token in line.
698 "var a = aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
699 " `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`;");
701 // Two template strings.
702 verifyFormat("var x = `hello` == `hello`;");
704 // Comments in template strings.
705 EXPECT_EQ("var x = `//a`;\n"
707 format("var x =\n `//a`;\n"
709 EXPECT_EQ("var x = `/*a`;\n"
711 format("var x =\n `/*a`;\n"
713 // Backticks in a comment - not a template string.
714 EXPECT_EQ("var x = 1 // `/*a`;\n"
716 format("var x =\n 1 // `/*a`;\n"
718 EXPECT_EQ("/* ` */ var x = 1; /* ` */",
719 format("/* ` */ var x\n= 1; /* ` */"));
720 // Comment spans multiple template strings.
721 EXPECT_EQ("var x = `/*a`;\n"
723 format("var x =\n `/*a`;\n"
724 "var y =\n ` */ `;"));
726 EXPECT_EQ("var x = ` \\` a`;\n"
728 format("var x = ` \\` a`;\n"
732 TEST_F(FormatTestJS, CastSyntax) {
733 verifyFormat("var x = <type>foo;");
736 TEST_F(FormatTestJS, TypeArguments) {
737 verifyFormat("class X<Y> {}");
738 verifyFormat("new X<Y>();");
739 verifyFormat("foo<Y>(a);");
740 verifyFormat("var x: X<Y>[];");
741 verifyFormat("class C extends D<E> implements F<G>, H<I> {}");
742 verifyFormat("function f(a: List<any> = null) {\n}");
743 verifyFormat("function f(): List<any> {\n}");
746 TEST_F(FormatTestJS, OptionalTypes) {
747 verifyFormat("function x(a?: b, c?, d?) {\n}");
748 verifyFormat("class X {\n"
752 verifyFormat("interface X {\n"
755 verifyFormat("x ? 1 : 2;");
756 verifyFormat("constructor({aa}: {\n"
758 " aaaaaaaa?: string,\n"
759 " aaaaaaaaaaaaaaa?: boolean,\n"
760 " aaaaaa?: List<string>\n"
765 TEST_F(FormatTestJS, IndexSignature) {
766 verifyFormat("var x: {[k: string]: v};");
769 } // end namespace tooling
770 } // end namespace clang