xref: /llvm-project/clang/unittests/Format/FormatTestJS.cpp (revision a4e55f4d1ec87056703c752644e12640e97fb5a1)
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     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");
31     return Result;
32   }
33 
34   static std::string format(
35       llvm::StringRef Code,
36       const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
37     return format(Code, 0, Code.size(), Style);
38   }
39 
40   static FormatStyle getGoogleJSStyleWithColumns(unsigned ColumnLimit) {
41     FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
42     Style.ColumnLimit = ColumnLimit;
43     return Style;
44   }
45 
46   static void verifyFormat(
47       llvm::StringRef Code,
48       const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
49     EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
50   }
51 };
52 
53 TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
54   verifyFormat("a == = b;");
55   verifyFormat("a != = b;");
56 
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"
62                "        d !==\n"
63                "    e + f + g)\n"
64                "  q();",
65                getGoogleJSStyleWithColumns(20));
66 
67   verifyFormat("a >> >= b;");
68 
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"
74                "        d >>>\n"
75                "    e + f + g)\n"
76                "  q();",
77                getGoogleJSStyleWithColumns(20));
78   verifyFormat("var x = aaaaaaaaaa ?\n"
79                "            bbbbbb :\n"
80                "            ccc;",
81                getGoogleJSStyleWithColumns(20));
82 
83   verifyFormat("var b = a.map((x) => x + 1);");
84   verifyFormat("return ('aaa') in bbbb;");
85 }
86 
87 TEST_F(FormatTestJS, UnderstandsAmpAmp) {
88   verifyFormat("e && e.SomeFunction();");
89 }
90 
91 TEST_F(FormatTestJS, LiteralOperatorsCanBeKeywords) {
92   verifyFormat("not.and.or.not_eq = 1;");
93 }
94 
95 TEST_F(FormatTestJS, ES6DestructuringAssignment) {
96   verifyFormat("var [a, b, c] = [1, 2, 3];");
97   verifyFormat("var {a, b} = {\n"
98                "  a: 1,\n"
99                "  b: 2\n"
100                "};");
101 }
102 
103 TEST_F(FormatTestJS, ContainerLiterals) {
104   verifyFormat("return {\n"
105                "  link: function() {\n"
106                "    f();  //\n"
107                "  }\n"
108                "};");
109   verifyFormat("return {\n"
110                "  a: a,\n"
111                "  link: function() {\n"
112                "    f();  //\n"
113                "  }\n"
114                "};");
115   verifyFormat("return {\n"
116                "  a: a,\n"
117                "  link: function() {\n"
118                "    f();  //\n"
119                "  },\n"
120                "  link: function() {\n"
121                "    f();  //\n"
122                "  }\n"
123                "};");
124   verifyFormat("var stuff = {\n"
125                "  // comment for update\n"
126                "  update: false,\n"
127                "  // comment for modules\n"
128                "  modules: false,\n"
129                "  // comment for tasks\n"
130                "  tasks: false\n"
131                "};");
132   verifyFormat("return {\n"
133                "  'finish':\n"
134                "      //\n"
135                "      a\n"
136                "};");
137   verifyFormat("var obj = {\n"
138                "  fooooooooo: function(x) {\n"
139                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
140                "  }\n"
141                "};");
142 }
143 
144 TEST_F(FormatTestJS, SpacesInContainerLiterals) {
145   verifyFormat("var arr = [1, 2, 3];");
146   verifyFormat("f({a: 1, b: 2, c: 3});");
147 
148   verifyFormat("var object_literal_with_long_name = {\n"
149                "  a: 'aaaaaaaaaaaaaaaaaa',\n"
150                "  b: 'bbbbbbbbbbbbbbbbbb'\n"
151                "};");
152 
153   verifyFormat("f({a: 1, b: 2, c: 3});",
154                getChromiumStyle(FormatStyle::LK_JavaScript));
155   verifyFormat("f({'a': [{}]});");
156 }
157 
158 TEST_F(FormatTestJS, SingleQuoteStrings) {
159   verifyFormat("this.function('', true);");
160 }
161 
162 TEST_F(FormatTestJS, GoogScopes) {
163   verifyFormat("goog.scope(function() {\n"
164                "var x = a.b;\n"
165                "var y = c.d;\n"
166                "});  // goog.scope");
167 }
168 
169 TEST_F(FormatTestJS, GoogModules) {
170   verifyFormat("goog.module('this.is.really.absurdly.long');",
171                getGoogleJSStyleWithColumns(40));
172   verifyFormat("goog.require('this.is.really.absurdly.long');",
173                getGoogleJSStyleWithColumns(40));
174   verifyFormat("goog.provide('this.is.really.absurdly.long');",
175                getGoogleJSStyleWithColumns(40));
176   verifyFormat("var long = goog.require('this.is.really.absurdly.long');",
177                getGoogleJSStyleWithColumns(40));
178 
179   // These should be wrapped normally.
180   verifyFormat(
181       "var MyLongClassName =\n"
182       "    goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
183 }
184 
185 TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
186   verifyFormat("function outer1(a, b) {\n"
187                "  function inner1(a, b) { return a; }\n"
188                "  inner1(a, b);\n"
189                "}\n"
190                "function outer2(a, b) {\n"
191                "  function inner2(a, b) { return a; }\n"
192                "  inner2(a, b);\n"
193                "}");
194 }
195 
196 TEST_F(FormatTestJS, FunctionLiterals) {
197   verifyFormat("doFoo(function() {});");
198   verifyFormat("doFoo(function() { return 1; });");
199   verifyFormat("var func = function() {\n"
200                "  return 1;\n"
201                "};");
202   verifyFormat("return {\n"
203                "  body: {\n"
204                "    setAttribute: function(key, val) { this[key] = val; },\n"
205                "    getAttribute: function(key) { return this[key]; },\n"
206                "    style: {direction: ''}\n"
207                "  }\n"
208                "};");
209   // FIXME: The formatting here probably isn't ideal.
210   EXPECT_EQ("abc = xyz ?\n"
211             "          function() {\n"
212             "            return 1;\n"
213             "          } :\n"
214             "          function() {\n"
215             "  return -1;\n"
216             "};",
217             format("abc=xyz?function(){return 1;}:function(){return -1;};"));
218 
219   verifyFormat("var closure = goog.bind(\n"
220                "    function() {  // comment\n"
221                "      foo();\n"
222                "      bar();\n"
223                "    },\n"
224                "    this, arg1IsReallyLongAndNeeedsLineBreaks,\n"
225                "    arg3IsReallyLongAndNeeedsLineBreaks);");
226   verifyFormat("var closure = goog.bind(function() {  // comment\n"
227                "  foo();\n"
228                "  bar();\n"
229                "}, this);");
230   verifyFormat("return {\n"
231                "  a: 'E',\n"
232                "  b: function() {\n"
233                "    return function() {\n"
234                "      f();  //\n"
235                "    };\n"
236                "  }\n"
237                "};");
238   verifyFormat("{\n"
239                "  var someVariable = function(x) {\n"
240                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
241                "  };\n"
242                "}");
243 
244   verifyFormat("f({a: function() { return 1; }});",
245                getGoogleJSStyleWithColumns(33));
246   verifyFormat("f({\n"
247                "  a: function() { return 1; }\n"
248                "});",
249                getGoogleJSStyleWithColumns(32));
250 
251   verifyFormat("return {\n"
252                "  a: function SomeFunction() {\n"
253                "    // ...\n"
254                "    return 1;\n"
255                "  }\n"
256                "};");
257 }
258 
259 TEST_F(FormatTestJS, InliningFunctionLiterals) {
260   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
261   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
262   verifyFormat("var func = function() {\n"
263                "  return 1;\n"
264                "};",
265                Style);
266   verifyFormat("var func = doSomething(function() { return 1; });", Style);
267   verifyFormat("var outer = function() {\n"
268                "  var inner = function() { return 1; }\n"
269                "};",
270                Style);
271   verifyFormat("function outer1(a, b) {\n"
272                "  function inner1(a, b) { return a; }\n"
273                "}",
274                Style);
275 
276   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
277   verifyFormat("var func = function() { return 1; };", Style);
278   verifyFormat("var func = doSomething(function() { return 1; });", Style);
279   verifyFormat(
280       "var outer = function() { var inner = function() { return 1; } };",
281       Style);
282   verifyFormat("function outer1(a, b) {\n"
283                "  function inner1(a, b) { return a; }\n"
284                "}",
285                Style);
286 
287   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
288   verifyFormat("var func = function() {\n"
289                "  return 1;\n"
290                "};",
291                Style);
292   verifyFormat("var func = doSomething(function() {\n"
293                "  return 1;\n"
294                "});",
295                Style);
296   verifyFormat("var outer = function() {\n"
297                "  var inner = function() {\n"
298                "    return 1;\n"
299                "  }\n"
300                "};",
301                Style);
302   verifyFormat("function outer1(a, b) {\n"
303                "  function inner1(a, b) {\n"
304                "    return a;\n"
305                "  }\n"
306                "}",
307                Style);
308 }
309 
310 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
311   verifyFormat("promise.then(\n"
312                "    function success() {\n"
313                "      doFoo();\n"
314                "      doBar();\n"
315                "    },\n"
316                "    function error() {\n"
317                "      doFoo();\n"
318                "      doBaz();\n"
319                "    },\n"
320                "    []);\n");
321   verifyFormat("promise.then(\n"
322                "    function success() {\n"
323                "      doFoo();\n"
324                "      doBar();\n"
325                "    },\n"
326                "    [],\n"
327                "    function error() {\n"
328                "      doFoo();\n"
329                "      doBaz();\n"
330                "    });\n");
331   // FIXME: Here, we should probably break right after the "(" for consistency.
332   verifyFormat("promise.then([],\n"
333                "             function success() {\n"
334                "               doFoo();\n"
335                "               doBar();\n"
336                "             },\n"
337                "             function error() {\n"
338                "               doFoo();\n"
339                "               doBaz();\n"
340                "             });\n");
341 
342   verifyFormat("getSomeLongPromise()\n"
343                "    .then(function(value) { body(); })\n"
344                "    .thenCatch(function(error) { body(); });");
345   verifyFormat("getSomeLongPromise()\n"
346                "    .then(function(value) {\n"
347                "      body();\n"
348                "      body();\n"
349                "    })\n"
350                "    .thenCatch(function(error) {\n"
351                "      body();\n"
352                "      body();\n"
353                "    });");
354 }
355 
356 TEST_F(FormatTestJS, ReturnStatements) {
357   verifyFormat("function() {\n"
358                "  return [hello, world];\n"
359                "}");
360 }
361 
362 TEST_F(FormatTestJS, ClosureStyleComments) {
363   verifyFormat("var x = /** @type {foo} */ (bar);");
364 }
365 
366 TEST_F(FormatTestJS, TryCatch) {
367   verifyFormat("try {\n"
368                "  f();\n"
369                "} catch (e) {\n"
370                "  g();\n"
371                "} finally {\n"
372                "  h();\n"
373                "}");
374 
375   // But, of course, "catch" is a perfectly fine function name in JavaScript.
376   verifyFormat("someObject.catch();");
377   verifyFormat("someObject.new();");
378   verifyFormat("someObject.delete();");
379 }
380 
381 TEST_F(FormatTestJS, StringLiteralConcatenation) {
382   verifyFormat("var literal = 'hello ' +\n"
383                "              'world';");
384 }
385 
386 TEST_F(FormatTestJS, RegexLiteralClassification) {
387   // Regex literals.
388   verifyFormat("var regex = /abc/;");
389   verifyFormat("f(/abc/);");
390   verifyFormat("f(abc, /abc/);");
391   verifyFormat("some_map[/abc/];");
392   verifyFormat("var x = a ? /abc/ : /abc/;");
393   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
394   verifyFormat("var x = !/abc/.test(y);");
395   verifyFormat("var x = a && /abc/.test(y);");
396   verifyFormat("var x = a || /abc/.test(y);");
397   verifyFormat("var x = a + /abc/.search(y);");
398   verifyFormat("var regexs = {/abc/, /abc/};");
399   verifyFormat("return /abc/;");
400 
401   // Not regex literals.
402   verifyFormat("var a = a / 2 + b / 3;");
403 }
404 
405 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
406   verifyFormat("var regex = /a*/;");
407   verifyFormat("var regex = /a+/;");
408   verifyFormat("var regex = /a?/;");
409   verifyFormat("var regex = /.a./;");
410   verifyFormat("var regex = /a\\*/;");
411   verifyFormat("var regex = /^a$/;");
412   verifyFormat("var regex = /\\/a/;");
413   verifyFormat("var regex = /(?:x)/;");
414   verifyFormat("var regex = /x(?=y)/;");
415   verifyFormat("var regex = /x(?!y)/;");
416   verifyFormat("var regex = /x|y/;");
417   verifyFormat("var regex = /a{2}/;");
418   verifyFormat("var regex = /a{1,3}/;");
419   verifyFormat("var regex = /[abc]/;");
420   verifyFormat("var regex = /[^abc]/;");
421   verifyFormat("var regex = /[\\b]/;");
422   verifyFormat("var regex = /\\b/;");
423   verifyFormat("var regex = /\\B/;");
424   verifyFormat("var regex = /\\d/;");
425   verifyFormat("var regex = /\\D/;");
426   verifyFormat("var regex = /\\f/;");
427   verifyFormat("var regex = /\\n/;");
428   verifyFormat("var regex = /\\r/;");
429   verifyFormat("var regex = /\\s/;");
430   verifyFormat("var regex = /\\S/;");
431   verifyFormat("var regex = /\\t/;");
432   verifyFormat("var regex = /\\v/;");
433   verifyFormat("var regex = /\\w/;");
434   verifyFormat("var regex = /\\W/;");
435   verifyFormat("var regex = /a(a)\\1/;");
436   verifyFormat("var regex = /\\0/;");
437   verifyFormat("var regex = /\\\\/g;");
438   verifyFormat("var regex = /\\a\\\\/g;");
439   verifyFormat("var regex = /\a\\//g;");
440   verifyFormat("var regex = /a\\//;\n"
441                "var x = 0;");
442   EXPECT_EQ("var regex = /\\/*/;\n"
443             "var x = 0;",
444             format("var regex = /\\/*/;\n"
445                    "var x=0;"));
446 }
447 
448 TEST_F(FormatTestJS, RegexLiteralModifiers) {
449   verifyFormat("var regex = /abc/g;");
450   verifyFormat("var regex = /abc/i;");
451   verifyFormat("var regex = /abc/m;");
452   verifyFormat("var regex = /abc/y;");
453 }
454 
455 TEST_F(FormatTestJS, RegexLiteralLength) {
456   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
457                getGoogleJSStyleWithColumns(60));
458   verifyFormat("var regex =\n"
459                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
460                getGoogleJSStyleWithColumns(60));
461 }
462 
463 TEST_F(FormatTestJS, RegexLiteralExamples) {
464   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
465 }
466 
467 } // end namespace tooling
468 } // end namespace clang
469