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