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