Debian Codegraph @

test/com/google/javascript/jscomp/CodePrinterTest.java

raw symbols SCIP
1 /*
2 * Copyright 2004 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Joiner;
20 import com.google.common.collect.Lists;
21 import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
22 import com.google.javascript.rhino.InputId;
23 import com.google.javascript.rhino.Node;
24 import com.google.javascript.rhino.Token;
25
26 import junit.framework.TestCase;
27
28 import java.util.List;
29
30 public class CodePrinterTest extends TestCase {
31 private boolean trustedStrings = true;
32 private Compiler lastCompiler = null;
33
34 @Override public void setUp() {
35 trustedStrings = true;
36 lastCompiler = null;
37 }
38
39 Node parse(String js) {
40 return parse(js, false);
41 }
42
43 Node parse(String js, boolean checkTypes) {
44 Compiler compiler = new Compiler();
45 lastCompiler = compiler;
46 CompilerOptions options = new CompilerOptions();
47 options.setTrustedStrings(trustedStrings);
48
49 // Allow getters and setters.
50 options.setLanguageIn(LanguageMode.ECMASCRIPT5);
51 compiler.initOptions(options);
52 Node n = compiler.parseTestCode(js);
53
54 if (checkTypes) {
55 DefaultPassConfig passConfig = new DefaultPassConfig(null);
56 CompilerPass typeResolver = passConfig.resolveTypes.create(compiler);
57 Node externs = new Node(Token.SCRIPT);
58 externs.setInputId(new InputId("externs"));
59 Node externAndJsRoot = new Node(Token.BLOCK, externs, n);
60 externAndJsRoot.setIsSyntheticBlock(true);
61 typeResolver.process(externs, n);
62 CompilerPass inferTypes = passConfig.inferTypes.create(compiler);
63 inferTypes.process(externs, n);
64 }
65
66 checkUnexpectedErrorsOrWarnings(compiler, 0);
67 return n;
68 }
69
70 private static void checkUnexpectedErrorsOrWarnings(
71 Compiler compiler, int expected) {
72 int actual = compiler.getErrors().length + compiler.getWarnings().length;
73 if (actual != expected) {
74 String msg = "";
75 for (JSError err : compiler.getErrors()) {
76 msg += "Error:" + err.toString() + "\n";
77 }
78 for (JSError err : compiler.getWarnings()) {
79 msg += "Warning:" + err.toString() + "\n";
80 }
81 assertEquals("Unexpected warnings or errors.\n " + msg, expected, actual);
82 }
83 }
84
85 String parsePrint(String js, boolean prettyprint, int lineThreshold) {
86 CompilerOptions options = new CompilerOptions();
87 options.setTrustedStrings(trustedStrings);
88 options.setPrettyPrint(prettyprint);
89 options.setLineLengthThreshold(lineThreshold);
90 return new CodePrinter.Builder(parse(js)).setCompilerOptions(options)
91 .build();
92 }
93
94 String parsePrint(String js, boolean prettyprint, boolean lineBreak,
95 int lineThreshold) {
96 CompilerOptions options = new CompilerOptions();
97 options.setTrustedStrings(trustedStrings);
98 options.setPrettyPrint(prettyprint);
99 options.setLineLengthThreshold(lineThreshold);
100 options.setLineBreak(lineBreak);
101 return new CodePrinter.Builder(parse(js)).setCompilerOptions(options)
102 .build();
103 }
104
105 String parsePrint(String js, boolean prettyprint, boolean lineBreak,
106 boolean preferLineBreakAtEof, int lineThreshold) {
107 CompilerOptions options = new CompilerOptions();
108 options.setTrustedStrings(trustedStrings);
109 options.setPrettyPrint(prettyprint);
110 options.setLineLengthThreshold(lineThreshold);
111 options.setPreferLineBreakAtEndOfFile(preferLineBreakAtEof);
112 options.setLineBreak(lineBreak);
113 return new CodePrinter.Builder(parse(js)).setCompilerOptions(options)
114 .build();
115 }
116
117 String parsePrint(String js, boolean prettyprint, boolean lineBreak,
118 int lineThreshold, boolean outputTypes) {
119 Node node = parse(js, true);
120 CompilerOptions options = new CompilerOptions();
121 options.setTrustedStrings(trustedStrings);
122 options.setPrettyPrint(prettyprint);
123 options.setLineLengthThreshold(lineThreshold);
124 options.setLineBreak(lineBreak);
125 return new CodePrinter.Builder(node).setCompilerOptions(options)
126 .setOutputTypes(outputTypes)
127 .setTypeRegistry(lastCompiler.getTypeRegistry())
128 .build();
129 }
130
131 String parsePrint(String js, boolean prettyprint, boolean lineBreak,
132 int lineThreshold, boolean outputTypes,
133 boolean tagAsStrict) {
134 Node node = parse(js, true);
135 CompilerOptions options = new CompilerOptions();
136 options.setTrustedStrings(trustedStrings);
137 options.setPrettyPrint(prettyprint);
138 options.setLineLengthThreshold(lineThreshold);
139 options.setLineBreak(lineBreak);
140 return new CodePrinter.Builder(node).setCompilerOptions(options)
141 .setOutputTypes(outputTypes)
142 .setTypeRegistry(lastCompiler.getTypeRegistry())
143 .setTagAsStrict(tagAsStrict)
144 .build();
145 }
146
147
148 String printNode(Node n) {
149 CompilerOptions options = new CompilerOptions();
150 options.setLineLengthThreshold(CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD);
151 return new CodePrinter.Builder(n).setCompilerOptions(options).build();
152 }
153
154 void assertPrintNode(String expectedJs, Node ast) {
155 assertEquals(expectedJs, printNode(ast));
156 }
157
158 public void testPrint() {
159 assertPrint("10 + a + b", "10+a+b");
160 assertPrint("10 + (30*50)", "10+30*50");
161 assertPrint("with(x) { x + 3; }", "with(x)x+3");
162 assertPrint("\"aa'a\"", "\"aa'a\"");
163 assertPrint("\"aa\\\"a\"", "'aa\"a'");
164 assertPrint("function foo()\n{return 10;}", "function foo(){return 10}");
165 assertPrint("a instanceof b", "a instanceof b");
166 assertPrint("typeof(a)", "typeof a");
167 assertPrint(
168 "var foo = x ? { a : 1 } : {a: 3, b:4, \"default\": 5, \"foo-bar\": 6}",
169 "var foo=x?{a:1}:{a:3,b:4,\"default\":5,\"foo-bar\":6}");
170
171 // Safari: needs ';' at the end of a throw statement
172 assertPrint("function foo(){throw 'error';}",
173 "function foo(){throw\"error\";}");
174 // Safari 3 needs a "{" around a single function
175 assertPrint("if (true) function foo(){return}",
176 "if(true){function foo(){return}}");
177
178 assertPrint("var x = 10; { var y = 20; }", "var x=10;var y=20");
179
180 assertPrint("while (x-- > 0);", "while(x-- >0);");
181 assertPrint("x-- >> 1", "x-- >>1");
182
183 assertPrint("(function () {})(); ",
184 "(function(){})()");
185
186 // Associativity
187 assertPrint("var a,b,c,d;a || (b&& c) && (a || d)",
188 "var a,b,c,d;a||b&&c&&(a||d)");
189 assertPrint("var a,b,c; a || (b || c); a * (b * c); a | (b | c)",
190 "var a,b,c;a||b||c;a*b*c;a|b|c");
191 assertPrint("var a,b,c; a / b / c;a / (b / c); a - (b - c);",
192 "var a,b,c;a/b/c;a/(b/c);a-(b-c)");
193 assertPrint("var a,b; a = b = 3;",
194 "var a,b;a=b=3");
195 assertPrint("var a,b,c,d; a = (b = c = (d = 3));",
196 "var a,b,c,d;a=b=c=d=3");
197 assertPrint("var a,b,c; a += (b = c += 3);",
198 "var a,b,c;a+=b=c+=3");
199 assertPrint("var a,b,c; a *= (b -= c);",
200 "var a,b,c;a*=b-=c");
201
202 // Precedence
203 assertPrint("a ? delete b[0] : 3", "a?delete b[0]:3");
204 assertPrint("(delete a[0])/10", "delete a[0]/10");
205
206 // optional '()' for new
207
208 // simple new
209 assertPrint("new A", "new A");
210 assertPrint("new A()", "new A");
211 assertPrint("new A('x')", "new A(\"x\")");
212
213 // calling instance method directly after new
214 assertPrint("new A().a()", "(new A).a()");
215 assertPrint("(new A).a()", "(new A).a()");
216
217 // this case should be fixed
218 assertPrint("new A('y').a()", "(new A(\"y\")).a()");
219
220 // internal class
221 assertPrint("new A.B", "new A.B");
222 assertPrint("new A.B()", "new A.B");
223 assertPrint("new A.B('z')", "new A.B(\"z\")");
224
225 // calling instance method directly after new internal class
226 assertPrint("(new A.B).a()", "(new A.B).a()");
227 assertPrint("new A.B().a()", "(new A.B).a()");
228 // this case should be fixed
229 assertPrint("new A.B('w').a()", "(new A.B(\"w\")).a()");
230
231 // Operators: make sure we don't convert binary + and unary + into ++
232 assertPrint("x + +y", "x+ +y");
233 assertPrint("x - (-y)", "x- -y");
234 assertPrint("x++ +y", "x++ +y");
235 assertPrint("x-- -y", "x-- -y");
236 assertPrint("x++ -y", "x++-y");
237
238 // Label
239 assertPrint("foo:for(;;){break foo;}", "foo:for(;;)break foo");
240 assertPrint("foo:while(1){continue foo;}", "foo:while(1)continue foo");
241
242 // Object literals.
243 assertPrint("({})", "({})");
244 assertPrint("var x = {};", "var x={}");
245 assertPrint("({}).x", "({}).x");
246 assertPrint("({})['x']", "({})[\"x\"]");
247 assertPrint("({}) instanceof Object", "({})instanceof Object");
248 assertPrint("({}) || 1", "({})||1");
249 assertPrint("1 || ({})", "1||{}");
250 assertPrint("({}) ? 1 : 2", "({})?1:2");
251 assertPrint("0 ? ({}) : 2", "0?{}:2");
252 assertPrint("0 ? 1 : ({})", "0?1:{}");
253 assertPrint("typeof ({})", "typeof{}");
254 assertPrint("f({})", "f({})");
255
256 // Anonymous function expressions.
257 assertPrint("(function(){})", "(function(){})");
258 assertPrint("(function(){})()", "(function(){})()");
259 assertPrint("(function(){})instanceof Object",
260 "(function(){})instanceof Object");
261 assertPrint("(function(){}).bind().call()",
262 "(function(){}).bind().call()");
263 assertPrint("var x = function() { };", "var x=function(){}");
264 assertPrint("var x = function() { }();", "var x=function(){}()");
265 assertPrint("(function() {}), 2", "(function(){}),2");
266
267 // Name functions expression.
268 assertPrint("(function f(){})", "(function f(){})");
269
270 // Function declaration.
271 assertPrint("function f(){}", "function f(){}");
272
273 // Make sure we don't treat non-Latin character escapes as raw strings.
274 assertPrint("({ 'a': 4, '\\u0100': 4 })", "({\"a\":4,\"\\u0100\":4})");
275 assertPrint("({ a: 4, '\\u0100': 4 })", "({a:4,\"\\u0100\":4})");
276
277 // Test if statement and for statements with single statements in body.
278 assertPrint("if (true) { alert();}", "if(true)alert()");
279 assertPrint("if (false) {} else {alert(\"a\");}",
280 "if(false);else alert(\"a\")");
281 assertPrint("for(;;) { alert();};", "for(;;)alert()");
282
283 assertPrint("do { alert(); } while(true);",
284 "do alert();while(true)");
285 assertPrint("myLabel: { alert();}",
286 "myLabel:alert()");
287 assertPrint("myLabel: for(;;) continue myLabel;",
288 "myLabel:for(;;)continue myLabel");
289
290 // Test nested var statement
291 assertPrint("if (true) var x; x = 4;", "if(true)var x;x=4");
292
293 // Non-latin identifier. Make sure we keep them escaped.
294 assertPrint("\\u00fb", "\\u00fb");
295 assertPrint("\\u00fa=1", "\\u00fa=1");
296 assertPrint("function \\u00f9(){}", "function \\u00f9(){}");
297 assertPrint("x.\\u00f8", "x.\\u00f8");
298 assertPrint("x.\\u00f8", "x.\\u00f8");
299 assertPrint("abc\\u4e00\\u4e01jkl", "abc\\u4e00\\u4e01jkl");
300
301 // Test the right-associative unary operators for spurious parens
302 assertPrint("! ! true", "!!true");
303 assertPrint("!(!(true))", "!!true");
304 assertPrint("typeof(void(0))", "typeof void 0");
305 assertPrint("typeof(void(!0))", "typeof void!0");
306 assertPrint("+ - + + - + 3", "+-+ +-+3"); // chained unary plus/minus
307 assertPrint("+(--x)", "+--x");
308 assertPrint("-(++x)", "-++x");
309
310 // needs a space to prevent an ambiguous parse
311 assertPrint("-(--x)", "- --x");
312 assertPrint("!(~~5)", "!~~5");
313 assertPrint("~(a/b)", "~(a/b)");
314
315 // Preserve parens to overcome greedy binding of NEW
316 assertPrint("new (foo.bar()).factory(baz)", "new (foo.bar().factory)(baz)");
317 assertPrint("new (bar()).factory(baz)", "new (bar().factory)(baz)");
318 assertPrint("new (new foobar(x)).factory(baz)",
319 "new (new foobar(x)).factory(baz)");
320
321 // Make sure that HOOK is right associative
322 assertPrint("a ? b : (c ? d : e)", "a?b:c?d:e");
323 assertPrint("a ? (b ? c : d) : e", "a?b?c:d:e");
324 assertPrint("(a ? b : c) ? d : e", "(a?b:c)?d:e");
325
326 // Test nested ifs
327 assertPrint("if (x) if (y); else;", "if(x)if(y);else;");
328
329 // Test comma.
330 assertPrint("a,b,c", "a,b,c");
331 assertPrint("(a,b),c", "a,b,c");
332 assertPrint("a,(b,c)", "a,b,c");
333 assertPrint("x=a,b,c", "x=a,b,c");
334 assertPrint("x=(a,b),c", "x=(a,b),c");
335 assertPrint("x=a,(b,c)", "x=a,b,c");
336 assertPrint("x=a,y=b,z=c", "x=a,y=b,z=c");
337 assertPrint("x=(a,y=b,z=c)", "x=(a,y=b,z=c)");
338 assertPrint("x=[a,b,c,d]", "x=[a,b,c,d]");
339 assertPrint("x=[(a,b,c),d]", "x=[(a,b,c),d]");
340 assertPrint("x=[(a,(b,c)),d]", "x=[(a,b,c),d]");
341 assertPrint("x=[a,(b,c,d)]", "x=[a,(b,c,d)]");
342 assertPrint("var x=(a,b)", "var x=(a,b)");
343 assertPrint("var x=a,b,c", "var x=a,b,c");
344 assertPrint("var x=(a,b),c", "var x=(a,b),c");
345 assertPrint("var x=a,b=(c,d)", "var x=a,b=(c,d)");
346 assertPrint("foo(a,b,c,d)", "foo(a,b,c,d)");
347 assertPrint("foo((a,b,c),d)", "foo((a,b,c),d)");
348 assertPrint("foo((a,(b,c)),d)", "foo((a,b,c),d)");
349 assertPrint("f(a+b,(c,d,(e,f,g)))", "f(a+b,(c,d,e,f,g))");
350 assertPrint("({}) , 1 , 2", "({}),1,2");
351 assertPrint("({}) , {} , {}", "({}),{},{}");
352
353 // EMPTY nodes
354 assertPrint("if (x){}", "if(x);");
355 assertPrint("if(x);", "if(x);");
356 assertPrint("if(x)if(y);", "if(x)if(y);");
357 assertPrint("if(x){if(y);}", "if(x)if(y);");
358 assertPrint("if(x){if(y){};;;}", "if(x)if(y);");
359 assertPrint("if(x){;;function y(){};;}", "if(x){function y(){}}");
360 }
361
362 public void testBreakTrustedStrings() {
363 // Break scripts
364 assertPrint("'<script>'", "\"<script>\"");
365 assertPrint("'</script>'", "\"\\x3c/script>\"");
366 assertPrint("\"</script> </SCRIPT>\"", "\"\\x3c/script> \\x3c/SCRIPT>\"");
367
368 assertPrint("'-->'", "\"--\\x3e\"");
369 assertPrint("']]>'", "\"]]\\x3e\"");
370 assertPrint("' --></script>'", "\" --\\x3e\\x3c/script>\"");
371
372 assertPrint("/--> <\\/script>/g", "/--\\x3e <\\/script>/g");
373
374 // Break HTML start comments. Certain versions of WebKit
375 // begin an HTML comment when they see this.
376 assertPrint("'<!-- I am a string -->'",
377 "\"\\x3c!-- I am a string --\\x3e\"");
378
379 assertPrint("'<=&>'", "\"<=&>\"");
380 }
381
382 public void testBreakUntrustedStrings() {
383 trustedStrings = false;
384
385 // Break scripts
386 assertPrint("'<script>'", "\"\\x3cscript\\x3e\"");
387 assertPrint("'</script>'", "\"\\x3c/script\\x3e\"");
388 assertPrint("\"</script> </SCRIPT>\"", "\"\\x3c/script\\x3e \\x3c/SCRIPT\\x3e\"");
389
390 assertPrint("'-->'", "\"--\\x3e\"");
391 assertPrint("']]>'", "\"]]\\x3e\"");
392 assertPrint("' --></script>'", "\" --\\x3e\\x3c/script\\x3e\"");
393
394 assertPrint("/--> <\\/script>/g", "/--\\x3e <\\/script>/g");
395
396 // Break HTML start comments. Certain versions of WebKit
397 // begin an HTML comment when they see this.
398 assertPrint("'<!-- I am a string -->'",
399 "\"\\x3c!-- I am a string --\\x3e\"");
400
401 assertPrint("'<=&>'", "\"\\x3c\\x3d\\x26\\x3e\"");
402 assertPrint("/(?=x)/", "/(?=x)/");
403 }
404
405 public void testPrintArray() {
406 assertPrint("[void 0, void 0]", "[void 0,void 0]");
407 assertPrint("[undefined, undefined]", "[undefined,undefined]");
408 assertPrint("[ , , , undefined]", "[,,,undefined]");
409 assertPrint("[ , , , 0]", "[,,,0]");
410 }
411
412 public void testHook() {
413 assertPrint("a ? b = 1 : c = 2", "a?b=1:c=2");
414 assertPrint("x = a ? b = 1 : c = 2", "x=a?b=1:c=2");
415 assertPrint("(x = a) ? b = 1 : c = 2", "(x=a)?b=1:c=2");
416
417 assertPrint("x, a ? b = 1 : c = 2", "x,a?b=1:c=2");
418 assertPrint("x, (a ? b = 1 : c = 2)", "x,a?b=1:c=2");
419 assertPrint("(x, a) ? b = 1 : c = 2", "(x,a)?b=1:c=2");
420
421 assertPrint("a ? (x, b) : c = 2", "a?(x,b):c=2");
422 assertPrint("a ? b = 1 : (x,c)", "a?b=1:(x,c)");
423
424 assertPrint("a ? b = 1 : c = 2 + x", "a?b=1:c=2+x");
425 assertPrint("(a ? b = 1 : c = 2) + x", "(a?b=1:c=2)+x");
426 assertPrint("a ? b = 1 : (c = 2) + x", "a?b=1:(c=2)+x");
427
428 assertPrint("a ? (b?1:2) : 3", "a?b?1:2:3");
429 }
430
431 public void testPrintInOperatorInForLoop() {
432 // Check for in expression in for's init expression.
433 // Check alone, with + (higher precedence), with ?: (lower precedence),
434 // and with conditional.
435 assertPrint("var a={}; for (var i = (\"length\" in a); i;) {}",
436 "var a={};for(var i=(\"length\"in a);i;);");
437 assertPrint("var a={}; for (var i = (\"length\" in a) ? 0 : 1; i;) {}",
438 "var a={};for(var i=(\"length\"in a)?0:1;i;);");
439 assertPrint("var a={}; for (var i = (\"length\" in a) + 1; i;) {}",
440 "var a={};for(var i=(\"length\"in a)+1;i;);");
441 assertPrint("var a={};for (var i = (\"length\" in a|| \"size\" in a);;);",
442 "var a={};for(var i=(\"length\"in a)||(\"size\"in a);;);");
443 assertPrint("var a={};for (var i = a || a || (\"size\" in a);;);",
444 "var a={};for(var i=a||a||(\"size\"in a);;);");
445
446 // Test works with unary operators and calls.
447 assertPrint("var a={}; for (var i = -(\"length\" in a); i;) {}",
448 "var a={};for(var i=-(\"length\"in a);i;);");
449 assertPrint("var a={};function b_(p){ return p;};" +
450 "for(var i=1,j=b_(\"length\" in a);;) {}",
451 "var a={};function b_(p){return p}" +
452 "for(var i=1,j=b_(\"length\"in a);;);");
453
454 // Test we correctly handle an in operator in the test clause.
455 assertPrint("var a={}; for (;(\"length\" in a);) {}",
456 "var a={};for(;\"length\"in a;);");
457 }
458
459 public void testLiteralProperty() {
460 assertPrint("(64).toString()", "(64).toString()");
461 }
462
463 private void assertPrint(String js, String expected) {
464 parse(expected); // validate the expected string is valid JS
465 assertEquals(expected,
466 parsePrint(js, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD));
467 }
468
469 private void assertPrintSame(String js) {
470 assertPrint(js, js);
471 }
472
473 // Make sure that the code generator doesn't associate an
474 // else clause with the wrong if clause.
475 public void testAmbiguousElseClauses() {
476 assertPrintNode("if(x)if(y);else;",
477 new Node(Token.IF,
478 Node.newString(Token.NAME, "x"),
479 new Node(Token.BLOCK,
480 new Node(Token.IF,
481 Node.newString(Token.NAME, "y"),
482 new Node(Token.BLOCK),
483
484 // ELSE clause for the inner if
485 new Node(Token.BLOCK)))));
486
487 assertPrintNode("if(x){if(y);}else;",
488 new Node(Token.IF,
489 Node.newString(Token.NAME, "x"),
490 new Node(Token.BLOCK,
491 new Node(Token.IF,
492 Node.newString(Token.NAME, "y"),
493 new Node(Token.BLOCK))),
494
495 // ELSE clause for the outer if
496 new Node(Token.BLOCK)));
497
498 assertPrintNode("if(x)if(y);else{if(z);}else;",
499 new Node(Token.IF,
500 Node.newString(Token.NAME, "x"),
501 new Node(Token.BLOCK,
502 new Node(Token.IF,
503 Node.newString(Token.NAME, "y"),
504 new Node(Token.BLOCK),
505 new Node(Token.BLOCK,
506 new Node(Token.IF,
507 Node.newString(Token.NAME, "z"),
508 new Node(Token.BLOCK))))),
509
510 // ELSE clause for the outermost if
511 new Node(Token.BLOCK)));
512 }
513
514 public void testLineBreak() {
515 // line break after function if in a statement context
516 assertLineBreak("function a() {}\n" +
517 "function b() {}",
518 "function a(){}\n" +
519 "function b(){}\n");
520
521 // line break after ; after a function
522 assertLineBreak("var a = {};\n" +
523 "a.foo = function () {}\n" +
524 "function b() {}",
525 "var a={};a.foo=function(){};\n" +
526 "function b(){}\n");
527
528 // break after comma after a function
529 assertLineBreak("var a = {\n" +
530 " b: function() {},\n" +
531 " c: function() {}\n" +
532 "};\n" +
533 "alert(a);",
534
535 "var a={b:function(){},\n" +
536 "c:function(){}};\n" +
537 "alert(a)");
538 }
539
540 private void assertLineBreak(String js, String expected) {
541 assertEquals(expected,
542 parsePrint(js, false, true,
543 CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD));
544 }
545
546 public void testPreferLineBreakAtEndOfFile() {
547 // short final line, no previous break, do nothing
548 assertLineBreakAtEndOfFile(
549 "\"1234567890\";",
550 "\"1234567890\"",
551 "\"1234567890\"");
552
553 // short final line, shift previous break to end
554 assertLineBreakAtEndOfFile(
555 "\"123456789012345678901234567890\";\"1234567890\"",
556 "\"123456789012345678901234567890\";\n\"1234567890\"",
557 "\"123456789012345678901234567890\"; \"1234567890\";\n");
558 assertLineBreakAtEndOfFile(
559 "var12345678901234567890123456 instanceof Object;",
560 "var12345678901234567890123456 instanceof\nObject",
561 "var12345678901234567890123456 instanceof Object;\n");
562
563 // long final line, no previous break, add a break at end
564 assertLineBreakAtEndOfFile(
565 "\"1234567890\";\"12345678901234567890\";",
566 "\"1234567890\";\"12345678901234567890\"",
567 "\"1234567890\";\"12345678901234567890\";\n");
568
569 // long final line, previous break, add a break at end
570 assertLineBreakAtEndOfFile(
571 "\"123456789012345678901234567890\";\"12345678901234567890\";",
572 "\"123456789012345678901234567890\";\n\"12345678901234567890\"",
573 "\"123456789012345678901234567890\";\n\"12345678901234567890\";\n");
574 }
575
576 private void assertLineBreakAtEndOfFile(String js,
577 String expectedWithoutBreakAtEnd, String expectedWithBreakAtEnd) {
578 assertEquals(expectedWithoutBreakAtEnd,
579 parsePrint(js, false, false, false, 30));
580 assertEquals(expectedWithBreakAtEnd,
581 parsePrint(js, false, false, true, 30));
582 }
583
584 public void testPrettyPrinter() {
585 // Ensure that the pretty printer inserts line breaks at appropriate
586 // places.
587 assertPrettyPrint("(function(){})();","(function() {\n})();\n");
588 assertPrettyPrint("var a = (function() {});alert(a);",
589 "var a = function() {\n};\nalert(a);\n");
590
591 // Check we correctly handle putting brackets around all if clauses so
592 // we can put breakpoints inside statements.
593 assertPrettyPrint("if (1) {}",
594 "if(1) {\n" +
595 "}\n");
596 assertPrettyPrint("if (1) {alert(\"\");}",
597 "if(1) {\n" +
598 " alert(\"\")\n" +
599 "}\n");
600 assertPrettyPrint("if (1)alert(\"\");",
601 "if(1) {\n" +
602 " alert(\"\")\n" +
603 "}\n");
604 assertPrettyPrint("if (1) {alert();alert();}",
605 "if(1) {\n" +
606 " alert();\n" +
607 " alert()\n" +
608 "}\n");
609
610 // Don't add blocks if they weren't there already.
611 assertPrettyPrint("label: alert();",
612 "label:alert();\n");
613
614 // But if statements and loops get blocks automagically.
615 assertPrettyPrint("if (1) alert();",
616 "if(1) {\n" +
617 " alert()\n" +
618 "}\n");
619 assertPrettyPrint("for (;;) alert();",
620 "for(;;) {\n" +
621 " alert()\n" +
622 "}\n");
623
624 assertPrettyPrint("while (1) alert();",
625 "while(1) {\n" +
626 " alert()\n" +
627 "}\n");
628
629 // Do we put else clauses in blocks?
630 assertPrettyPrint("if (1) {} else {alert(a);}",
631 "if(1) {\n" +
632 "}else {\n alert(a)\n}\n");
633
634 // Do we add blocks to else clauses?
635 assertPrettyPrint("if (1) alert(a); else alert(b);",
636 "if(1) {\n" +
637 " alert(a)\n" +
638 "}else {\n" +
639 " alert(b)\n" +
640 "}\n");
641
642 // Do we put for bodies in blocks?
643 assertPrettyPrint("for(;;) { alert();}",
644 "for(;;) {\n" +
645 " alert()\n" +
646 "}\n");
647 assertPrettyPrint("for(;;) {}",
648 "for(;;) {\n" +
649 "}\n");
650 assertPrettyPrint("for(;;) { alert(); alert(); }",
651 "for(;;) {\n" +
652 " alert();\n" +
653 " alert()\n" +
654 "}\n");
655
656 // How about do loops?
657 assertPrettyPrint("do { alert(); } while(true);",
658 "do {\n" +
659 " alert()\n" +
660 "}while(true);\n");
661
662 // label?
663 assertPrettyPrint("myLabel: { alert();}",
664 "myLabel: {\n" +
665 " alert()\n" +
666 "}\n");
667
668 // Don't move the label on a loop, because then break {label} and
669 // continue {label} won't work.
670 assertPrettyPrint("myLabel: for(;;) continue myLabel;",
671 "myLabel:for(;;) {\n" +
672 " continue myLabel\n" +
673 "}\n");
674
675 assertPrettyPrint("var a;", "var a;\n");
676 }
677
678 public void testPrettyPrinter2() {
679 assertPrettyPrint(
680 "if(true) f();",
681 "if(true) {\n" +
682 " f()\n" +
683 "}\n");
684
685 assertPrettyPrint(
686 "if (true) { f() } else { g() }",
687 "if(true) {\n" +
688 " f()\n" +
689 "}else {\n" +
690 " g()\n" +
691 "}\n");
692
693 assertPrettyPrint(
694 "if(true) f(); for(;;) g();",
695 "if(true) {\n" +
696 " f()\n" +
697 "}\n" +
698 "for(;;) {\n" +
699 " g()\n" +
700 "}\n");
701 }
702
703 public void testPrettyPrinter3() {
704 assertPrettyPrint(
705 "try {} catch(e) {}if (1) {alert();alert();}",
706 "try {\n" +
707 "}catch(e) {\n" +
708 "}\n" +
709 "if(1) {\n" +
710 " alert();\n" +
711 " alert()\n" +
712 "}\n");
713
714 assertPrettyPrint(
715 "try {} finally {}if (1) {alert();alert();}",
716 "try {\n" +
717 "}finally {\n" +
718 "}\n" +
719 "if(1) {\n" +
720 " alert();\n" +
721 " alert()\n" +
722 "}\n");
723
724 assertPrettyPrint(
725 "try {} catch(e) {} finally {} if (1) {alert();alert();}",
726 "try {\n" +
727 "}catch(e) {\n" +
728 "}finally {\n" +
729 "}\n" +
730 "if(1) {\n" +
731 " alert();\n" +
732 " alert()\n" +
733 "}\n");
734 }
735
736 public void testPrettyPrinter4() {
737 assertPrettyPrint(
738 "function f() {}if (1) {alert();}",
739 "function f() {\n" +
740 "}\n" +
741 "if(1) {\n" +
742 " alert()\n" +
743 "}\n");
744
745 assertPrettyPrint(
746 "var f = function() {};if (1) {alert();}",
747 "var f = function() {\n" +
748 "};\n" +
749 "if(1) {\n" +
750 " alert()\n" +
751 "}\n");
752
753 assertPrettyPrint(
754 "(function() {})();if (1) {alert();}",
755 "(function() {\n" +
756 "})();\n" +
757 "if(1) {\n" +
758 " alert()\n" +
759 "}\n");
760
761 assertPrettyPrint(
762 "(function() {alert();alert();})();if (1) {alert();}",
763 "(function() {\n" +
764 " alert();\n" +
765 " alert()\n" +
766 "})();\n" +
767 "if(1) {\n" +
768 " alert()\n" +
769 "}\n");
770 }
771
772 public void testTypeAnnotations() {
773 assertTypeAnnotations(
774 "/** @constructor */ function Foo(){}",
775 "/**\n * @return {undefined}\n * @constructor\n */\n"
776 + "function Foo() {\n}\n");
777 }
778
779 public void testTypeAnnotationsTypeDef() {
780 // TODO(johnlenz): It would be nice if there were some way to preserve
781 // typedefs but currently they are resolved into the basic types in the
782 // type registry.
783 assertTypeAnnotations(
784 "/** @typedef {Array.<number>} */ goog.java.Long;\n"
785 + "/** @param {!goog.java.Long} a*/\n"
786 + "function f(a){};\n",
787 "goog.java.Long;\n"
788 + "/**\n"
789 + " * @param {(Array.<number>|null)} a\n"
790 + " * @return {undefined}\n"
791 + " */\n"
792 + "function f(a) {\n}\n");
793 }
794
795 public void testTypeAnnotationsAssign() {
796 assertTypeAnnotations("/** @constructor */ var Foo = function(){}",
797 "/**\n * @return {undefined}\n * @constructor\n */\n"
798 + "var Foo = function() {\n};\n");
799 }
800
801 public void testTypeAnnotationsNamespace() {
802 assertTypeAnnotations("var a = {};"
803 + "/** @constructor */ a.Foo = function(){}",
804 "var a = {};\n"
805 + "/**\n * @return {undefined}\n * @constructor\n */\n"
806 + "a.Foo = function() {\n};\n");
807 }
808
809 public void testTypeAnnotationsMemberSubclass() {
810 assertTypeAnnotations("var a = {};"
811 + "/** @constructor */ a.Foo = function(){};"
812 + "/** @constructor \n @extends {a.Foo} */ a.Bar = function(){}",
813 "var a = {};\n"
814 + "/**\n * @return {undefined}\n * @constructor\n */\n"
815 + "a.Foo = function() {\n};\n"
816 + "/**\n * @return {undefined}\n * @extends {a.Foo}\n"
817 + " * @constructor\n */\n"
818 + "a.Bar = function() {\n};\n");
819 }
820
821 public void testTypeAnnotationsInterface() {
822 assertTypeAnnotations("var a = {};"
823 + "/** @interface */ a.Foo = function(){};"
824 + "/** @interface \n @extends {a.Foo} */ a.Bar = function(){}",
825 "var a = {};\n"
826 + "/**\n * @interface\n */\n"
827 + "a.Foo = function() {\n};\n"
828 + "/**\n * @extends {a.Foo}\n"
829 + " * @interface\n */\n"
830 + "a.Bar = function() {\n};\n");
831 }
832
833 public void testTypeAnnotationsMultipleInterface() {
834 assertTypeAnnotations("var a = {};"
835 + "/** @interface */ a.Foo1 = function(){};"
836 + "/** @interface */ a.Foo2 = function(){};"
837 + "/** @interface \n @extends {a.Foo1} \n @extends {a.Foo2} */"
838 + "a.Bar = function(){}",
839 "var a = {};\n"
840 + "/**\n * @interface\n */\n"
841 + "a.Foo1 = function() {\n};\n"
842 + "/**\n * @interface\n */\n"
843 + "a.Foo2 = function() {\n};\n"
844 + "/**\n * @extends {a.Foo1}\n"
845 + " * @extends {a.Foo2}\n"
846 + " * @interface\n */\n"
847 + "a.Bar = function() {\n};\n");
848 }
849
850 public void testTypeAnnotationsMember() {
851 assertTypeAnnotations("var a = {};"
852 + "/** @constructor */ a.Foo = function(){}"
853 + "/** @param {string} foo\n"
854 + " * @return {number} */\n"
855 + "a.Foo.prototype.foo = function(foo) { return 3; };"
856 + "/** @type {string|undefined} */"
857 + "a.Foo.prototype.bar = '';",
858 "var a = {};\n"
859 + "/**\n * @return {undefined}\n * @constructor\n */\n"
860 + "a.Foo = function() {\n};\n"
861 + "/**\n"
862 + " * @param {string} foo\n"
863 + " * @return {number}\n"
864 + " */\n"
865 + "a.Foo.prototype.foo = function(foo) {\n return 3\n};\n"
866 + "/** @type {string} */\n"
867 + "a.Foo.prototype.bar = \"\";\n");
868 }
869
870 public void testTypeAnnotationsImplements() {
871 assertTypeAnnotations("var a = {};"
872 + "/** @constructor */ a.Foo = function(){};\n"
873 + "/** @interface */ a.I = function(){};\n"
874 + "/** @interface */ a.I2 = function(){};\n"
875 + "/** @constructor \n @extends {a.Foo}\n"
876 + " * @implements {a.I} \n @implements {a.I2}\n"
877 + "*/ a.Bar = function(){}",
878 "var a = {};\n"
879 + "/**\n * @return {undefined}\n * @constructor\n */\n"
880 + "a.Foo = function() {\n};\n"
881 + "/**\n * @interface\n */\n"
882 + "a.I = function() {\n};\n"
883 + "/**\n * @interface\n */\n"
884 + "a.I2 = function() {\n};\n"
885 + "/**\n * @return {undefined}\n * @extends {a.Foo}\n"
886 + " * @implements {a.I}\n"
887 + " * @implements {a.I2}\n * @constructor\n */\n"
888 + "a.Bar = function() {\n};\n");
889 }
890
891 public void testTypeAnnotationsDispatcher1() {
892 assertTypeAnnotations(
893 "var a = {};\n" +
894 "/** \n" +
895 " * @constructor \n" +
896 " * @javadispatch \n" +
897 " */\n" +
898 "a.Foo = function(){}",
899 "var a = {};\n" +
900 "/**\n" +
901 " * @return {undefined}\n" +
902 " * @constructor\n" +
903 " * @javadispatch\n" +
904 " */\n" +
905 "a.Foo = function() {\n" +
906 "};\n");
907 }
908
909 public void testTypeAnnotationsDispatcher2() {
910 assertTypeAnnotations(
911 "var a = {};\n" +
912 "/** \n" +
913 " * @constructor \n" +
914 " */\n" +
915 "a.Foo = function(){}\n" +
916 "/**\n" +
917 " * @javadispatch\n" +
918 " */\n" +
919 "a.Foo.prototype.foo = function() {};",
920
921 "var a = {};\n" +
922 "/**\n" +
923 " * @return {undefined}\n" +
924 " * @constructor\n" +
925 " */\n" +
926 "a.Foo = function() {\n" +
927 "};\n" +
928 "/**\n" +
929 " * @return {undefined}\n" +
930 " * @javadispatch\n" +
931 " */\n" +
932 "a.Foo.prototype.foo = function() {\n" +
933 "};\n");
934 }
935
936 public void testU2UFunctionTypeAnnotation1() {
937 assertTypeAnnotations(
938 "/** @type {!Function} */ var x = function() {}",
939 "/** @type {!Function} */\n" +
940 "var x = function() {\n};\n");
941 }
942
943 public void testU2UFunctionTypeAnnotation2() {
944 // TODO(johnlenz): we currently report the type of the RHS which is not
945 // correct, we should export the type of the LHS.
946 assertTypeAnnotations(
947 "/** @type {Function} */ var x = function() {}",
948 "/** @type {!Function} */\n" +
949 "var x = function() {\n};\n");
950 }
951
952 public void testEmitUnknownParamTypesAsAllType() {
953 assertTypeAnnotations(
954 "var a = function(x) {}",
955 "/**\n" +
956 " * @param {?} x\n" +
957 " * @return {undefined}\n" +
958 " */\n" +
959 "var a = function(x) {\n};\n");
960 }
961
962 public void testOptionalTypesAnnotation() {
963 assertTypeAnnotations(
964 "/**\n" +
965 " * @param {string=} x \n" +
966 " */\n" +
967 "var a = function(x) {}",
968 "/**\n" +
969 " * @param {string=} x\n" +
970 " * @return {undefined}\n" +
971 " */\n" +
972 "var a = function(x) {\n};\n");
973 }
974
975 public void testVariableArgumentsTypesAnnotation() {
976 assertTypeAnnotations(
977 "/**\n" +
978 " * @param {...string} x \n" +
979 " */\n" +
980 "var a = function(x) {}",
981 "/**\n" +
982 " * @param {...string} x\n" +
983 " * @return {undefined}\n" +
984 " */\n" +
985 "var a = function(x) {\n};\n");
986 }
987
988 public void testTempConstructor() {
989 assertTypeAnnotations(
990 "var x = function() {\n/**\n * @constructor\n */\nfunction t1() {}\n" +
991 " /**\n * @constructor\n */\nfunction t2() {}\n" +
992 " t1.prototype = t2.prototype}",
993 "/**\n * @return {undefined}\n */\nvar x = function() {\n" +
994 " /**\n * @return {undefined}\n * @constructor\n */\n" +
995 "function t1() {\n }\n" +
996 " /**\n * @return {undefined}\n * @constructor\n */\n" +
997 "function t2() {\n }\n" +
998 " t1.prototype = t2.prototype\n};\n"
999 );
1000 }
1001
1002 public void testEnumAnnotation1() {
1003 assertTypeAnnotations(
1004 "/** @enum {string} */ var Enum = {FOO: 'x', BAR: 'y'};",
1005 "/** @enum {string} */\nvar Enum = {FOO:\"x\", BAR:\"y\"};\n");
1006 }
1007
1008 public void testEnumAnnotation2() {
1009 assertTypeAnnotations(
1010 "var goog = goog || {};" +
1011 "/** @enum {string} */ goog.Enum = {FOO: 'x', BAR: 'y'};" +
1012 "/** @const */ goog.Enum2 = goog.x ? {} : goog.Enum;",
1013 "var goog = goog || {};\n" +
1014 "/** @enum {string} */\ngoog.Enum = {FOO:\"x\", BAR:\"y\"};\n" +
1015 "/** @type {(Object|{})} */\ngoog.Enum2 = goog.x ? {} : goog.Enum;\n");
1016 }
1017
1018 private void assertPrettyPrint(String js, String expected) {
1019 assertEquals(expected,
1020 parsePrint(js, true, false,
1021 CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD));
1022 }
1023
1024 private void assertTypeAnnotations(String js, String expected) {
1025 assertEquals(expected,
1026 parsePrint(js, true, false,
1027 CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD, true));
1028 }
1029
1030 public void testSubtraction() {
1031 Compiler compiler = new Compiler();
1032 Node n = compiler.parseTestCode("x - -4");
1033 assertEquals(0, compiler.getErrorCount());
1034
1035 assertEquals(
1036 "x- -4",
1037 printNode(n));
1038 }
1039
1040 public void testFunctionWithCall() {
1041 assertPrint(
1042 "var user = new function() {"
1043 + "alert(\"foo\")}",
1044 "var user=new function(){"
1045 + "alert(\"foo\")}");
1046 assertPrint(
1047 "var user = new function() {"
1048 + "this.name = \"foo\";"
1049 + "this.local = function(){alert(this.name)};}",
1050 "var user=new function(){"
1051 + "this.name=\"foo\";"
1052 + "this.local=function(){alert(this.name)}}");
1053 }
1054
1055 public void testLineLength() {
1056 // list
1057 assertLineLength("var aba,bcb,cdc",
1058 "var aba,bcb," +
1059 "\ncdc");
1060
1061 // operators, and two breaks
1062 assertLineLength(
1063 "\"foo\"+\"bar,baz,bomb\"+\"whee\"+\";long-string\"\n+\"aaa\"",
1064 "\"foo\"+\"bar,baz,bomb\"+" +
1065 "\n\"whee\"+\";long-string\"+" +
1066 "\n\"aaa\"");
1067
1068 // assignment
1069 assertLineLength("var abazaba=1234",
1070 "var abazaba=" +
1071 "\n1234");
1072
1073 // statements
1074 assertLineLength("var abab=1;var bab=2",
1075 "var abab=1;" +
1076 "\nvar bab=2");
1077
1078 // don't break regexes
1079 assertLineLength("var a=/some[reg](ex),with.*we?rd|chars/i;var b=a",
1080 "var a=/some[reg](ex),with.*we?rd|chars/i;" +
1081 "\nvar b=a");
1082
1083 // don't break strings
1084 assertLineLength("var a=\"foo,{bar};baz\";var b=a",
1085 "var a=\"foo,{bar};baz\";" +
1086 "\nvar b=a");
1087
1088 // don't break before post inc/dec
1089 assertLineLength("var a=\"a\";a++;var b=\"bbb\";",
1090 "var a=\"a\";a++;\n" +
1091 "var b=\"bbb\"");
1092 }
1093
1094 private void assertLineLength(String js, String expected) {
1095 assertEquals(expected,
1096 parsePrint(js, false, true, 10));
1097 }
1098
1099 public void testParsePrintParse() {
1100 testReparse("3;");
1101 testReparse("var a = b;");
1102 testReparse("var x, y, z;");
1103 testReparse("try { foo() } catch(e) { bar() }");
1104 testReparse("try { foo() } catch(e) { bar() } finally { stuff() }");
1105 testReparse("try { foo() } finally { stuff() }");
1106 testReparse("throw 'me'");
1107 testReparse("function foo(a) { return a + 4; }");
1108 testReparse("function foo() { return; }");
1109 testReparse("var a = function(a, b) { foo(); return a + b; }");
1110 testReparse("b = [3, 4, 'paul', \"Buchhe it\",,5];");
1111 testReparse("v = (5, 6, 7, 8)");
1112 testReparse("d = 34.0; x = 0; y = .3; z = -22");
1113 testReparse("d = -x; t = !x + ~y;");
1114 testReparse("'hi'; /* just a test */ stuff(a,b) \n" +
1115 " foo(); // and another \n" +
1116 " bar();");
1117 testReparse("a = b++ + ++c; a = b++-++c; a = - --b; a = - ++b;");
1118 testReparse("a++; b= a++; b = ++a; b = a--; b = --a; a+=2; b-=5");
1119 testReparse("a = (2 + 3) * 4;");
1120 testReparse("a = 1 + (2 + 3) + 4;");
1121 testReparse("x = a ? b : c; x = a ? (b,3,5) : (foo(),bar());");
1122 testReparse("a = b | c || d ^ e " +
1123 "&& f & !g != h << i <= j < k >>> l > m * n % !o");
1124 testReparse("a == b; a != b; a === b; a == b == a;" +
1125 " (a == b) == a; a == (b == a);");
1126 testReparse("if (a > b) a = b; if (b < 3) a = 3; else c = 4;");
1127 testReparse("if (a == b) { a++; } if (a == 0) { a++; } else { a --; }");
1128 testReparse("for (var i in a) b += i;");
1129 testReparse("for (var i = 0; i < 10; i++){ b /= 2;" +
1130 " if (b == 2)break;else continue;}");
1131 testReparse("for (x = 0; x < 10; x++) a /= 2;");
1132 testReparse("for (;;) a++;");
1133 testReparse("while(true) { blah(); }while(true) blah();");
1134 testReparse("do stuff(); while(a>b);");
1135 testReparse("[0, null, , true, false, this];");
1136 testReparse("s.replace(/absc/, 'X').replace(/ab/gi, 'Y');");
1137 testReparse("new Foo; new Bar(a, b,c);");
1138 testReparse("with(foo()) { x = z; y = t; } with(bar()) a = z;");
1139 testReparse("delete foo['bar']; delete foo;");
1140 testReparse("var x = { 'a':'paul', 1:'3', 2:(3,4) };");
1141 testReparse("switch(a) { case 2: case 3: stuff(); break;" +
1142 "case 4: morestuff(); break; default: done();}");
1143 testReparse("x = foo['bar'] + foo['my stuff'] + foo[bar] + f.stuff;");
1144 testReparse("a.v = b.v; x['foo'] = y['zoo'];");
1145 testReparse("'test' in x; 3 in x; a in x;");
1146 testReparse("'foo\"bar' + \"foo'c\" + 'stuff\\n and \\\\more'");
1147 testReparse("x.__proto__;");
1148 }
1149
1150 private void testReparse(String code) {
1151 Compiler compiler = new Compiler();
1152 Node parse1 = parse(code);
1153 Node parse2 = parse(new CodePrinter.Builder(parse1).build());
1154 String explanation = parse1.checkTreeEquals(parse2);
1155 assertNull("\nExpected: " + compiler.toSource(parse1) +
1156 "\nResult: " + compiler.toSource(parse2) +
1157 "\n" + explanation, explanation);
1158 }
1159
1160 public void testDoLoopIECompatiblity() {
1161 // Do loops within IFs cause syntax errors in IE6 and IE7.
1162 assertPrint("function f(){if(e1){do foo();while(e2)}else foo()}",
1163 "function f(){if(e1){do foo();while(e2)}else foo()}");
1164
1165 assertPrint("function f(){if(e1)do foo();while(e2)else foo()}",
1166 "function f(){if(e1){do foo();while(e2)}else foo()}");
1167
1168 assertPrint("if(x){do{foo()}while(y)}else bar()",
1169 "if(x){do foo();while(y)}else bar()");
1170
1171 assertPrint("if(x)do{foo()}while(y);else bar()",
1172 "if(x){do foo();while(y)}else bar()");
1173
1174 assertPrint("if(x){do{foo()}while(y)}",
1175 "if(x){do foo();while(y)}");
1176
1177 assertPrint("if(x)do{foo()}while(y);",
1178 "if(x){do foo();while(y)}");
1179
1180 assertPrint("if(x)A:do{foo()}while(y);",
1181 "if(x){A:do foo();while(y)}");
1182
1183 assertPrint("var i = 0;a: do{b: do{i++;break b;} while(0);} while(0);",
1184 "var i=0;a:do{b:do{i++;break b}while(0)}while(0)");
1185 }
1186
1187 public void testFunctionSafariCompatiblity() {
1188 // Functions within IFs cause syntax errors on Safari.
1189 assertPrint("function f(){if(e1){function goo(){return true}}else foo()}",
1190 "function f(){if(e1){function goo(){return true}}else foo()}");
1191
1192 assertPrint("function f(){if(e1)function goo(){return true}else foo()}",
1193 "function f(){if(e1){function goo(){return true}}else foo()}");
1194
1195 assertPrint("if(e1){function goo(){return true}}",
1196 "if(e1){function goo(){return true}}");
1197
1198 assertPrint("if(e1)function goo(){return true}",
1199 "if(e1){function goo(){return true}}");
1200
1201 assertPrint("if(e1)A:function goo(){return true}",
1202 "if(e1){A:function goo(){return true}}");
1203 }
1204
1205 public void testExponents() {
1206 assertPrintNumber("1", 1);
1207 assertPrintNumber("10", 10);
1208 assertPrintNumber("100", 100);
1209 assertPrintNumber("1E3", 1000);
1210 assertPrintNumber("1E4", 10000);
1211 assertPrintNumber("1E5", 100000);
1212 assertPrintNumber("-1", -1);
1213 assertPrintNumber("-10", -10);
1214 assertPrintNumber("-100", -100);
1215 assertPrintNumber("-1E3", -1000);
1216 assertPrintNumber("-12341234E4", -123412340000L);
1217 assertPrintNumber("1E18", 1000000000000000000L);
1218 assertPrintNumber("1E5", 100000.0);
1219 assertPrintNumber("100000.1", 100000.1);
1220
1221 assertPrintNumber("1E-6", 0.000001);
1222 assertPrintNumber("-0x38d7ea4c68001", -0x38d7ea4c68001L);
1223 assertPrintNumber("0x38d7ea4c68001", 0x38d7ea4c68001L);
1224 }
1225
1226 // Make sure to test as both a String and a Node, because
1227 // negative numbers do not parse consistently from strings.
1228 private void assertPrintNumber(String expected, double number) {
1229 assertPrint(String.valueOf(number), expected);
1230 assertPrintNode(expected, Node.newNumber(number));
1231 }
1232
1233 private void assertPrintNumber(String expected, int number) {
1234 assertPrint(String.valueOf(number), expected);
1235 assertPrintNode(expected, Node.newNumber(number));
1236 }
1237
1238 public void testDirectEval() {
1239 assertPrint("eval('1');", "eval(\"1\")");
1240 }
1241
1242 public void testIndirectEval() {
1243 Node n = parse("eval('1');");
1244 assertPrintNode("eval(\"1\")", n);
1245 n.getFirstChild().getFirstChild().getFirstChild().putBooleanProp(
1246 Node.DIRECT_EVAL, false);
1247 assertPrintNode("(0,eval)(\"1\")", n);
1248 }
1249
1250 public void testFreeCall1() {
1251 assertPrint("foo(a);", "foo(a)");
1252 assertPrint("x.foo(a);", "x.foo(a)");
1253 }
1254
1255 public void testFreeCall2() {
1256 Node n = parse("foo(a);");
1257 assertPrintNode("foo(a)", n);
1258 Node call = n.getFirstChild().getFirstChild();
1259 assertTrue(call.isCall());
1260 call.putBooleanProp(Node.FREE_CALL, true);
1261 assertPrintNode("foo(a)", n);
1262 }
1263
1264 public void testFreeCall3() {
1265 Node n = parse("x.foo(a);");
1266 assertPrintNode("x.foo(a)", n);
1267 Node call = n.getFirstChild().getFirstChild();
1268 assertTrue(call.isCall());
1269 call.putBooleanProp(Node.FREE_CALL, true);
1270 assertPrintNode("(0,x.foo)(a)", n);
1271 }
1272
1273 public void testPrintScript() {
1274 // Verify that SCRIPT nodes not marked as synthetic are printed as
1275 // blocks.
1276 Node ast = new Node(Token.SCRIPT,
1277 new Node(Token.EXPR_RESULT, Node.newString("f")),
1278 new Node(Token.EXPR_RESULT, Node.newString("g")));
1279 String result = new CodePrinter.Builder(ast).setPrettyPrint(true).build();
1280 assertEquals("\"f\";\n\"g\";\n", result);
1281 }
1282
1283 public void testObjectLit() {
1284 assertPrint("({x:1})", "({x:1})");
1285 assertPrint("var x=({x:1})", "var x={x:1}");
1286 assertPrint("var x={'x':1}", "var x={\"x\":1}");
1287 assertPrint("var x={1:1}", "var x={1:1}");
1288 assertPrint("({},42)+0", "({},42)+0");
1289 }
1290
1291 public void testObjectLit2() {
1292 assertPrint("var x={1:1}", "var x={1:1}");
1293 assertPrint("var x={'1':1}", "var x={1:1}");
1294 assertPrint("var x={'1.0':1}", "var x={\"1.0\":1}");
1295 assertPrint("var x={1.5:1}", "var x={\"1.5\":1}");
1296
1297 }
1298
1299 public void testObjectLit3() {
1300 assertPrint("var x={3E9:1}",
1301 "var x={3E9:1}");
1302 assertPrint("var x={'3000000000':1}", // More than 31 bits
1303 "var x={3E9:1}");
1304 assertPrint("var x={'3000000001':1}",
1305 "var x={3000000001:1}");
1306 assertPrint("var x={'6000000001':1}", // More than 32 bits
1307 "var x={6000000001:1}");
1308 assertPrint("var x={\"12345678901234567\":1}", // More than 53 bits
1309 "var x={\"12345678901234567\":1}");
1310 }
1311
1312 public void testObjectLit4() {
1313 // More than 128 bits.
1314 assertPrint(
1315 "var x={\"123456789012345671234567890123456712345678901234567\":1}",
1316 "var x={\"123456789012345671234567890123456712345678901234567\":1}");
1317 }
1318
1319 public void testGetter() {
1320 assertPrint("var x = {}", "var x={}");
1321 assertPrint("var x = {get a() {return 1}}", "var x={get a(){return 1}}");
1322 assertPrint(
1323 "var x = {get a() {}, get b(){}}",
1324 "var x={get a(){},get b(){}}");
1325
1326 assertPrint(
1327 "var x = {get 'a'() {return 1}}",
1328 "var x={get \"a\"(){return 1}}");
1329
1330 assertPrint(
1331 "var x = {get 1() {return 1}}",
1332 "var x={get 1(){return 1}}");
1333
1334 assertPrint(
1335 "var x = {get \"()\"() {return 1}}",
1336 "var x={get \"()\"(){return 1}}");
1337 }
1338
1339 public void testSetter() {
1340 assertPrint("var x = {}", "var x={}");
1341 assertPrint(
1342 "var x = {set a(y) {return 1}}",
1343 "var x={set a(y){return 1}}");
1344
1345 assertPrint(
1346 "var x = {get 'a'() {return 1}}",
1347 "var x={get \"a\"(){return 1}}");
1348
1349 assertPrint(
1350 "var x = {set 1(y) {return 1}}",
1351 "var x={set 1(y){return 1}}");
1352
1353 assertPrint(
1354 "var x = {set \"(x)\"(y) {return 1}}",
1355 "var x={set \"(x)\"(y){return 1}}");
1356 }
1357
1358 public void testNegCollapse() {
1359 // Collapse the negative symbol on numbers at generation time,
1360 // to match the Rhino behavior.
1361 assertPrint("var x = - - 2;", "var x=2");
1362 assertPrint("var x = - (2);", "var x=-2");
1363 }
1364
1365 public void testStrict() {
1366 String result = parsePrint("var x", false, false, 0, false, true);
1367 assertEquals("'use strict';var x", result);
1368 }
1369
1370 public void testArrayLiteral() {
1371 assertPrint("var x = [,];","var x=[,]");
1372 assertPrint("var x = [,,];","var x=[,,]");
1373 assertPrint("var x = [,s,,];","var x=[,s,,]");
1374 assertPrint("var x = [,s];","var x=[,s]");
1375 assertPrint("var x = [s,];","var x=[s]");
1376 }
1377
1378 public void testZero() {
1379 assertPrint("var x ='\\0';", "var x=\"\\x00\"");
1380 assertPrint("var x ='\\x00';", "var x=\"\\x00\"");
1381 assertPrint("var x ='\\u0000';", "var x=\"\\x00\"");
1382 assertPrint("var x ='\\u00003';", "var x=\"\\x003\"");
1383 }
1384
1385 public void testUnicode() {
1386 assertPrint("var x ='\\x0f';", "var x=\"\\u000f\"");
1387 assertPrint("var x ='\\x68';", "var x=\"h\"");
1388 assertPrint("var x ='\\x7f';", "var x=\"\\u007f\"");
1389 }
1390
1391 public void testUnicodeKeyword() {
1392 // keyword "if"
1393 assertPrint("var \\u0069\\u0066 = 1;", "var i\\u0066=1");
1394 // keyword "var"
1395 assertPrint("var v\\u0061\\u0072 = 1;", "var va\\u0072=1");
1396 // all are keyword "while"
1397 assertPrint("var w\\u0068\\u0069\\u006C\\u0065 = 1;"
1398 + "\\u0077\\u0068il\\u0065 = 2;"
1399 + "\\u0077h\\u0069le = 3;",
1400 "var whil\\u0065=1;whil\\u0065=2;whil\\u0065=3");
1401 }
1402
1403 public void testNumericKeys() {
1404 assertPrint("var x = {010: 1};", "var x={8:1}");
1405 assertPrint("var x = {'010': 1};", "var x={\"010\":1}");
1406
1407 assertPrint("var x = {0x10: 1};", "var x={16:1}");
1408 assertPrint("var x = {'0x10': 1};", "var x={\"0x10\":1}");
1409
1410 // I was surprised at this result too.
1411 assertPrint("var x = {.2: 1};", "var x={\"0.2\":1}");
1412 assertPrint("var x = {'.2': 1};", "var x={\".2\":1}");
1413
1414 assertPrint("var x = {0.2: 1};", "var x={\"0.2\":1}");
1415 assertPrint("var x = {'0.2': 1};", "var x={\"0.2\":1}");
1416 }
1417
1418 public void testIssue582() {
1419 assertPrint("var x = -0.0;", "var x=-0");
1420 }
1421
1422 public void testIssue601() {
1423 assertPrint("'\\v' == 'v'", "\"\\v\"==\"v\"");
1424 assertPrint("'\\u000B' == '\\v'", "\"\\x0B\"==\"\\v\"");
1425 assertPrint("'\\x0B' == '\\v'", "\"\\x0B\"==\"\\v\"");
1426 }
1427
1428 public void testIssue620() {
1429 assertPrint("alert(/ / / / /);", "alert(/ // / /)");
1430 assertPrint("alert(/ // / /);", "alert(/ // / /)");
1431 }
1432
1433 public void testIssue5746867() {
1434 assertPrint("var a = { '$\\\\' : 5 };", "var a={\"$\\\\\":5}");
1435 }
1436
1437 public void testCommaSpacing() {
1438 assertPrint("var a = (b = 5, c = 5);",
1439 "var a=(b=5,c=5)");
1440 assertPrettyPrint("var a = (b = 5, c = 5);",
1441 "var a = (b = 5, c = 5);\n");
1442 }
1443
1444 public void testManyCommas() {
1445 int numCommas = 10000;
1446 List<String> numbers = Lists.newArrayList("0", "1");
1447 Node current = new Node(Token.COMMA, Node.newNumber(0), Node.newNumber(1));
1448 for (int i = 2; i < numCommas; i++) {
1449 current = new Node(Token.COMMA, current);
1450
1451 // 1000 is printed as 1E3, and screws up our test.
1452 int num = i % 1000;
1453 numbers.add(String.valueOf(num));
1454 current.addChildToBack(Node.newNumber(num));
1455 }
1456
1457 String expected = Joiner.on(",").join(numbers);
1458 String actual = printNode(current).replace("\n", "");
1459 assertEquals(expected, actual);
1460 }
1461
1462 public void testManyAdds() {
1463 int numAdds = 10000;
1464 List<String> numbers = Lists.newArrayList("0", "1");
1465 Node current = new Node(Token.ADD, Node.newNumber(0), Node.newNumber(1));
1466 for (int i = 2; i < numAdds; i++) {
1467 current = new Node(Token.ADD, current);
1468
1469 // 1000 is printed as 1E3, and screws up our test.
1470 int num = i % 1000;
1471 numbers.add(String.valueOf(num));
1472 current.addChildToBack(Node.newNumber(num));
1473 }
1474
1475 String expected = Joiner.on("+").join(numbers);
1476 String actual = printNode(current).replace("\n", "");
1477 assertEquals(expected, actual);
1478 }
1479
1480 public void testMinusNegativeZero() {
1481 // Negative zero is weird, because we have to be able to distinguish
1482 // it from positive zero (there are some subtle differences in behavior).
1483 assertPrint("x- -0", "x- -0");
1484 }
1485
1486 public void testStringEscapeSequences() {
1487 // From the SingleEscapeCharacter grammar production.
1488 assertPrintSame("var x=\"\\b\"");
1489 assertPrintSame("var x=\"\\f\"");
1490 assertPrintSame("var x=\"\\n\"");
1491 assertPrintSame("var x=\"\\r\"");
1492 assertPrintSame("var x=\"\\t\"");
1493 assertPrintSame("var x=\"\\v\"");
1494 assertPrint("var x=\"\\\"\"", "var x='\"'");
1495 assertPrint("var x=\"\\\'\"", "var x=\"'\"");
1496
1497 // From the LineTerminator grammar
1498 assertPrint("var x=\"\\u000A\"", "var x=\"\\n\"");
1499 assertPrint("var x=\"\\u000D\"", "var x=\"\\r\"");
1500 assertPrintSame("var x=\"\\u2028\"");
1501 assertPrintSame("var x=\"\\u2029\"");
1502
1503 // Now with regular expressions.
1504 assertPrintSame("var x=/\\b/");
1505 assertPrintSame("var x=/\\f/");
1506 assertPrintSame("var x=/\\n/");
1507 assertPrintSame("var x=/\\r/");
1508 assertPrintSame("var x=/\\t/");
1509 assertPrintSame("var x=/\\v/");
1510 assertPrintSame("var x=/\\u000A/");
1511 assertPrintSame("var x=/\\u000D/");
1512 assertPrintSame("var x=/\\u2028/");
1513 assertPrintSame("var x=/\\u2029/");
1514 }
1515 }