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:
format(llvm::StringRef Code,unsigned Offset,unsigned Length,const FormatStyle & Style)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 
format(llvm::StringRef Code,const FormatStyle & Style=getGoogleStyle (FormatStyle::LK_JavaScript))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 
getGoogleJSStyleWithColumns(unsigned ColumnLimit)40   static FormatStyle getGoogleJSStyleWithColumns(unsigned ColumnLimit) {
41     FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
42     Style.ColumnLimit = ColumnLimit;
43     return Style;
44   }
45 
verifyFormat(llvm::StringRef Code,const FormatStyle & Style=getGoogleStyle (FormatStyle::LK_JavaScript))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 
TEST_F(FormatTestJS,UnderstandsJavaScriptOperators)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 
TEST_F(FormatTestJS,UnderstandsAmpAmp)87 TEST_F(FormatTestJS, UnderstandsAmpAmp) {
88   verifyFormat("e && e.SomeFunction();");
89 }
90 
TEST_F(FormatTestJS,LiteralOperatorsCanBeKeywords)91 TEST_F(FormatTestJS, LiteralOperatorsCanBeKeywords) {
92   verifyFormat("not.and.or.not_eq = 1;");
93 }
94 
TEST_F(FormatTestJS,ES6DestructuringAssignment)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 
TEST_F(FormatTestJS,ContainerLiterals)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 
TEST_F(FormatTestJS,SpacesInContainerLiterals)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 
TEST_F(FormatTestJS,SingleQuoteStrings)158 TEST_F(FormatTestJS, SingleQuoteStrings) {
159   verifyFormat("this.function('', true);");
160 }
161 
TEST_F(FormatTestJS,GoogScopes)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 
TEST_F(FormatTestJS,GoogModules)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 
TEST_F(FormatTestJS,FormatsFreestandingFunctions)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 
TEST_F(FormatTestJS,FunctionLiterals)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   EXPECT_EQ("abc = xyz ?\n"
210             "          function() {\n"
211             "            return 1;\n"
212             "          } :\n"
213             "          function() {\n"
214             "            return -1;\n"
215             "          };",
216             format("abc=xyz?function(){return 1;}:function(){return -1;};"));
217 
218   verifyFormat("var closure = goog.bind(\n"
219                "    function() {  // comment\n"
220                "      foo();\n"
221                "      bar();\n"
222                "    },\n"
223                "    this, arg1IsReallyLongAndNeeedsLineBreaks,\n"
224                "    arg3IsReallyLongAndNeeedsLineBreaks);");
225   verifyFormat("var closure = goog.bind(function() {  // comment\n"
226                "  foo();\n"
227                "  bar();\n"
228                "}, this);");
229   verifyFormat("return {\n"
230                "  a: 'E',\n"
231                "  b: function() {\n"
232                "    return function() {\n"
233                "      f();  //\n"
234                "    };\n"
235                "  }\n"
236                "};");
237   verifyFormat("{\n"
238                "  var someVariable = function(x) {\n"
239                "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
240                "  };\n"
241                "}");
242 
243   verifyFormat("f({a: function() { return 1; }});",
244                getGoogleJSStyleWithColumns(33));
245   verifyFormat("f({\n"
246                "  a: function() { return 1; }\n"
247                "});",
248                getGoogleJSStyleWithColumns(32));
249 
250   verifyFormat("return {\n"
251                "  a: function SomeFunction() {\n"
252                "    // ...\n"
253                "    return 1;\n"
254                "  }\n"
255                "};");
256   verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
257                "    .then(goog.bind(function(aaaaaaaaaaa) {\n"
258                "      someFunction();\n"
259                "      someFunction();\n"
260                "    }, this), aaaaaaaaaaaaaaaaa);");
261 
262   // FIXME: This is not ideal yet.
263   verifyFormat("someFunction(goog.bind(\n"
264                "                 function() {\n"
265                "                   doSomething();\n"
266                "                   doSomething();\n"
267                "                 },\n"
268                "                 this),\n"
269                "             goog.bind(function() {\n"
270                "               doSomething();\n"
271                "               doSomething();\n"
272                "             }, this));");
273 }
274 
TEST_F(FormatTestJS,InliningFunctionLiterals)275 TEST_F(FormatTestJS, InliningFunctionLiterals) {
276   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
277   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
278   verifyFormat("var func = function() {\n"
279                "  return 1;\n"
280                "};",
281                Style);
282   verifyFormat("var func = doSomething(function() { return 1; });", Style);
283   verifyFormat("var outer = function() {\n"
284                "  var inner = function() { return 1; }\n"
285                "};",
286                Style);
287   verifyFormat("function outer1(a, b) {\n"
288                "  function inner1(a, b) { return a; }\n"
289                "}",
290                Style);
291 
292   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
293   verifyFormat("var func = function() { return 1; };", Style);
294   verifyFormat("var func = doSomething(function() { return 1; });", Style);
295   verifyFormat(
296       "var outer = function() { var inner = function() { return 1; } };",
297       Style);
298   verifyFormat("function outer1(a, b) {\n"
299                "  function inner1(a, b) { return a; }\n"
300                "}",
301                Style);
302 
303   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
304   verifyFormat("var func = function() {\n"
305                "  return 1;\n"
306                "};",
307                Style);
308   verifyFormat("var func = doSomething(function() {\n"
309                "  return 1;\n"
310                "});",
311                Style);
312   verifyFormat("var outer = function() {\n"
313                "  var inner = function() {\n"
314                "    return 1;\n"
315                "  }\n"
316                "};",
317                Style);
318   verifyFormat("function outer1(a, b) {\n"
319                "  function inner1(a, b) {\n"
320                "    return a;\n"
321                "  }\n"
322                "}",
323                Style);
324 }
325 
TEST_F(FormatTestJS,MultipleFunctionLiterals)326 TEST_F(FormatTestJS, MultipleFunctionLiterals) {
327   verifyFormat("promise.then(\n"
328                "    function success() {\n"
329                "      doFoo();\n"
330                "      doBar();\n"
331                "    },\n"
332                "    function error() {\n"
333                "      doFoo();\n"
334                "      doBaz();\n"
335                "    },\n"
336                "    []);\n");
337   verifyFormat("promise.then(\n"
338                "    function success() {\n"
339                "      doFoo();\n"
340                "      doBar();\n"
341                "    },\n"
342                "    [],\n"
343                "    function error() {\n"
344                "      doFoo();\n"
345                "      doBaz();\n"
346                "    });\n");
347   // FIXME: Here, we should probably break right after the "(" for consistency.
348   verifyFormat("promise.then([],\n"
349                "             function success() {\n"
350                "               doFoo();\n"
351                "               doBar();\n"
352                "             },\n"
353                "             function error() {\n"
354                "               doFoo();\n"
355                "               doBaz();\n"
356                "             });\n");
357 
358   verifyFormat("getSomeLongPromise()\n"
359                "    .then(function(value) { body(); })\n"
360                "    .thenCatch(function(error) {\n"
361                "      body();\n"
362                "      body();\n"
363                "    });");
364   verifyFormat("getSomeLongPromise()\n"
365                "    .then(function(value) {\n"
366                "      body();\n"
367                "      body();\n"
368                "    })\n"
369                "    .thenCatch(function(error) {\n"
370                "      body();\n"
371                "      body();\n"
372                "    });");
373 
374   // FIXME: This is bad, but it used to be formatted correctly by accident.
375   verifyFormat("getSomeLongPromise().then(function(value) {\n"
376                "  body();\n"
377                "}).thenCatch(function(error) { body(); });");
378 }
379 
TEST_F(FormatTestJS,ReturnStatements)380 TEST_F(FormatTestJS, ReturnStatements) {
381   verifyFormat("function() {\n"
382                "  return [hello, world];\n"
383                "}");
384 }
385 
TEST_F(FormatTestJS,ClosureStyleComments)386 TEST_F(FormatTestJS, ClosureStyleComments) {
387   verifyFormat("var x = /** @type {foo} */ (bar);");
388 }
389 
TEST_F(FormatTestJS,TryCatch)390 TEST_F(FormatTestJS, TryCatch) {
391   verifyFormat("try {\n"
392                "  f();\n"
393                "} catch (e) {\n"
394                "  g();\n"
395                "} finally {\n"
396                "  h();\n"
397                "}");
398 
399   // But, of course, "catch" is a perfectly fine function name in JavaScript.
400   verifyFormat("someObject.catch();");
401   verifyFormat("someObject.new();");
402   verifyFormat("someObject.delete();");
403 }
404 
TEST_F(FormatTestJS,StringLiteralConcatenation)405 TEST_F(FormatTestJS, StringLiteralConcatenation) {
406   verifyFormat("var literal = 'hello ' +\n"
407                "              'world';");
408 }
409 
TEST_F(FormatTestJS,RegexLiteralClassification)410 TEST_F(FormatTestJS, RegexLiteralClassification) {
411   // Regex literals.
412   verifyFormat("var regex = /abc/;");
413   verifyFormat("f(/abc/);");
414   verifyFormat("f(abc, /abc/);");
415   verifyFormat("some_map[/abc/];");
416   verifyFormat("var x = a ? /abc/ : /abc/;");
417   verifyFormat("for (var i = 0; /abc/.test(s[i]); i++) {\n}");
418   verifyFormat("var x = !/abc/.test(y);");
419   verifyFormat("var x = a && /abc/.test(y);");
420   verifyFormat("var x = a || /abc/.test(y);");
421   verifyFormat("var x = a + /abc/.search(y);");
422   verifyFormat("var regexs = {/abc/, /abc/};");
423   verifyFormat("return /abc/;");
424 
425   // Not regex literals.
426   verifyFormat("var a = a / 2 + b / 3;");
427 }
428 
TEST_F(FormatTestJS,RegexLiteralSpecialCharacters)429 TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
430   verifyFormat("var regex = /a*/;");
431   verifyFormat("var regex = /a+/;");
432   verifyFormat("var regex = /a?/;");
433   verifyFormat("var regex = /.a./;");
434   verifyFormat("var regex = /a\\*/;");
435   verifyFormat("var regex = /^a$/;");
436   verifyFormat("var regex = /\\/a/;");
437   verifyFormat("var regex = /(?:x)/;");
438   verifyFormat("var regex = /x(?=y)/;");
439   verifyFormat("var regex = /x(?!y)/;");
440   verifyFormat("var regex = /x|y/;");
441   verifyFormat("var regex = /a{2}/;");
442   verifyFormat("var regex = /a{1,3}/;");
443   verifyFormat("var regex = /[abc]/;");
444   verifyFormat("var regex = /[^abc]/;");
445   verifyFormat("var regex = /[\\b]/;");
446   verifyFormat("var regex = /\\b/;");
447   verifyFormat("var regex = /\\B/;");
448   verifyFormat("var regex = /\\d/;");
449   verifyFormat("var regex = /\\D/;");
450   verifyFormat("var regex = /\\f/;");
451   verifyFormat("var regex = /\\n/;");
452   verifyFormat("var regex = /\\r/;");
453   verifyFormat("var regex = /\\s/;");
454   verifyFormat("var regex = /\\S/;");
455   verifyFormat("var regex = /\\t/;");
456   verifyFormat("var regex = /\\v/;");
457   verifyFormat("var regex = /\\w/;");
458   verifyFormat("var regex = /\\W/;");
459   verifyFormat("var regex = /a(a)\\1/;");
460   verifyFormat("var regex = /\\0/;");
461   verifyFormat("var regex = /\\\\/g;");
462   verifyFormat("var regex = /\\a\\\\/g;");
463   verifyFormat("var regex = /\a\\//g;");
464   verifyFormat("var regex = /a\\//;\n"
465                "var x = 0;");
466   EXPECT_EQ("var regex = /\\/*/;\n"
467             "var x = 0;",
468             format("var regex = /\\/*/;\n"
469                    "var x=0;"));
470 }
471 
TEST_F(FormatTestJS,RegexLiteralModifiers)472 TEST_F(FormatTestJS, RegexLiteralModifiers) {
473   verifyFormat("var regex = /abc/g;");
474   verifyFormat("var regex = /abc/i;");
475   verifyFormat("var regex = /abc/m;");
476   verifyFormat("var regex = /abc/y;");
477 }
478 
TEST_F(FormatTestJS,RegexLiteralLength)479 TEST_F(FormatTestJS, RegexLiteralLength) {
480   verifyFormat("var regex = /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
481                getGoogleJSStyleWithColumns(60));
482   verifyFormat("var regex =\n"
483                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
484                getGoogleJSStyleWithColumns(60));
485   verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
486                getGoogleJSStyleWithColumns(50));
487 }
488 
TEST_F(FormatTestJS,RegexLiteralExamples)489 TEST_F(FormatTestJS, RegexLiteralExamples) {
490   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
491 }
492 
493 } // end namespace tooling
494 } // end namespace clang
495