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