Debian Codegraph @

src/com/google/javascript/jscomp/CodeGenerator.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.Charsets;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.Maps;
22 import com.google.javascript.rhino.Node;
23 import com.google.javascript.rhino.Token;
24 import com.google.javascript.rhino.TokenStream;
25
26 import java.io.IOException;
27 import java.nio.charset.Charset;
28 import java.nio.charset.CharsetEncoder;
29 import java.util.Map;
30
31 /**
32 * CodeGenerator generates codes from a parse tree, sending it to the specified
33 * CodeConsumer.
34 *
35 */
36 class CodeGenerator {
37 private static final String LT_ESCAPED = "\\x3c";
38 private static final String GT_ESCAPED = "\\x3e";
39
40 // A memoizer for formatting strings as JS strings.
41 private final Map<String, String> ESCAPED_JS_STRINGS = Maps.newHashMap();
42
43 private static final char[] HEX_CHARS
44 = { '0', '1', '2', '3', '4', '5', '6', '7',
45 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
46
47 private final CodeConsumer cc;
48
49 private final CharsetEncoder outputCharsetEncoder;
50
51 private final boolean preferSingleQuotes;
52 private final boolean trustedStrings;
53
54 private CodeGenerator(CodeConsumer consumer) {
55 cc = consumer;
56 outputCharsetEncoder = null;
57 preferSingleQuotes = false;
58 trustedStrings = true;
59 }
60
61 static CodeGenerator forCostEstimation(CodeConsumer consumer) {
62 return new CodeGenerator(consumer);
63 }
64
65 CodeGenerator(
66 CodeConsumer consumer,
67 CompilerOptions options) {
68 cc = consumer;
69
70 Charset outputCharset = options.getOutputCharset();
71 if (outputCharset == null || outputCharset == Charsets.US_ASCII) {
72 // If we want our default (pretending to be UTF-8, but escaping anything
73 // outside of straight ASCII), then don't use the encoder, but
74 // just special-case the code. This keeps the normal path through
75 // the code identical to how it's been for years.
76 this.outputCharsetEncoder = null;
77 } else {
78 this.outputCharsetEncoder = outputCharset.newEncoder();
79 }
80 this.preferSingleQuotes = options.preferSingleQuotes;
81 this.trustedStrings = options.trustedStrings;
82 }
83
84 /**
85 * Insert a ECMASCRIPT 5 strict annotation.
86 */
87 public void tagAsStrict() {
88 add("'use strict';");
89 }
90
91 void add(String str) {
92 cc.add(str);
93 }
94
95 private void addIdentifier(String identifier) {
96 cc.addIdentifier(identifierEscape(identifier));
97 }
98
99 void add(Node n) {
100 add(n, Context.OTHER);
101 }
102
103 void add(Node n, Context context) {
104 if (!cc.continueProcessing()) {
105 return;
106 }
107
108 int type = n.getType();
109 String opstr = NodeUtil.opToStr(type);
110 int childCount = n.getChildCount();
111 Node first = n.getFirstChild();
112 Node last = n.getLastChild();
113
114 // Handle all binary operators
115 if (opstr != null && first != last) {
116 Preconditions.checkState(
117 childCount == 2,
118 "Bad binary operator \"%s\": expected 2 arguments but got %s",
119 opstr, childCount);
120 int p = NodeUtil.precedence(type);
121
122 // For right-hand-side of operations, only pass context if it's
123 // the IN_FOR_INIT_CLAUSE one.
124 Context rhsContext = getContextForNoInOperator(context);
125
126 // Handle associativity.
127 // e.g. if the parse tree is a * (b * c),
128 // we can simply generate a * b * c.
129 if (last.getType() == type &&
130 NodeUtil.isAssociative(type)) {
131 addExpr(first, p, context);
132 cc.addOp(opstr, true);
133 addExpr(last, p, rhsContext);
134 } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) {
135 // Assignments are the only right-associative binary operators
136 addExpr(first, p, context);
137 cc.addOp(opstr, true);
138 addExpr(last, p, rhsContext);
139 } else {
140 unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1);
141 }
142 return;
143 }
144
145 cc.startSourceMapping(n);
146
147 switch (type) {
148 case Token.TRY: {
149 Preconditions.checkState(first.getNext().isBlock() &&
150 !first.getNext().hasMoreThanOneChild());
151 Preconditions.checkState(childCount >= 2 && childCount <= 3);
152
153 add("try");
154 add(first, Context.PRESERVE_BLOCK);
155
156 // second child contains the catch block, or nothing if there
157 // isn't a catch block
158 Node catchblock = first.getNext().getFirstChild();
159 if (catchblock != null) {
160 add(catchblock);
161 }
162
163 if (childCount == 3) {
164 add("finally");
165 add(last, Context.PRESERVE_BLOCK);
166 }
167 break;
168 }
169
170 case Token.CATCH:
171 Preconditions.checkState(childCount == 2);
172 add("catch(");
173 add(first);
174 add(")");
175 add(last, Context.PRESERVE_BLOCK);
176 break;
177
178 case Token.THROW:
179 Preconditions.checkState(childCount == 1);
180 add("throw");
181 add(first);
182
183 // Must have a ';' after a throw statement, otherwise safari can't
184 // parse this.
185 cc.endStatement(true);
186 break;
187
188 case Token.RETURN:
189 add("return");
190 if (childCount == 1) {
191 add(first);
192 } else {
193 Preconditions.checkState(childCount == 0);
194 }
195 cc.endStatement();
196 break;
197
198 case Token.VAR:
199 if (first != null) {
200 add("var ");
201 addList(first, false, getContextForNoInOperator(context));
202 }
203 break;
204
205 case Token.LABEL_NAME:
206 Preconditions.checkState(!n.getString().isEmpty());
207 addIdentifier(n.getString());
208 break;
209
210 case Token.NAME:
211 if (first == null || first.isEmpty()) {
212 addIdentifier(n.getString());
213 } else {
214 Preconditions.checkState(childCount == 1);
215 addIdentifier(n.getString());
216 cc.addOp("=", true);
217 if (first.isComma()) {
218 addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER);
219 } else {
220 // Add expression, consider nearby code at lowest level of
221 // precedence.
222 addExpr(first, 0, getContextForNoInOperator(context));
223 }
224 }
225 break;
226
227 case Token.ARRAYLIT:
228 add("[");
229 addArrayList(first);
230 add("]");
231 break;
232
233 case Token.PARAM_LIST:
234 add("(");
235 addList(first);
236 add(")");
237 break;
238
239 case Token.COMMA:
240 Preconditions.checkState(childCount == 2);
241 unrollBinaryOperator(n, Token.COMMA, ",", context, Context.OTHER, 0, 0);
242 break;
243
244 case Token.NUMBER:
245 Preconditions.checkState(childCount == 0);
246 cc.addNumber(n.getDouble());
247 break;
248
249 case Token.TYPEOF:
250 case Token.VOID:
251 case Token.NOT:
252 case Token.BITNOT:
253 case Token.POS: {
254 // All of these unary operators are right-associative
255 Preconditions.checkState(childCount == 1);
256 cc.addOp(NodeUtil.opToStrNoFail(type), false);
257 addExpr(first, NodeUtil.precedence(type), Context.OTHER);
258 break;
259 }
260
261 case Token.NEG: {
262 Preconditions.checkState(childCount == 1);
263
264 // It's important to our sanity checker that the code
265 // we print produces the same AST as the code we parse back.
266 // NEG is a weird case because Rhino parses "- -2" as "2".
267 if (n.getFirstChild().isNumber()) {
268 cc.addNumber(-n.getFirstChild().getDouble());
269 } else {
270 cc.addOp(NodeUtil.opToStrNoFail(type), false);
271 addExpr(first, NodeUtil.precedence(type), Context.OTHER);
272 }
273
274 break;
275 }
276
277 case Token.HOOK: {
278 Preconditions.checkState(childCount == 3);
279 int p = NodeUtil.precedence(type);
280 addExpr(first, p + 1, context);
281 cc.addOp("?", true);
282 addExpr(first.getNext(), 1, Context.OTHER);
283 cc.addOp(":", true);
284 addExpr(last, 1, Context.OTHER);
285 break;
286 }
287
288 case Token.REGEXP:
289 if (!first.isString() ||
290 !last.isString()) {
291 throw new Error("Expected children to be strings");
292 }
293
294 String regexp = regexpEscape(first.getString(), outputCharsetEncoder);
295
296 // I only use one .add because whitespace matters
297 if (childCount == 2) {
298 add(regexp + last.getString());
299 } else {
300 Preconditions.checkState(childCount == 1);
301 add(regexp);
302 }
303 break;
304
305 case Token.FUNCTION:
306 if (n.getClass() != Node.class) {
307 throw new Error("Unexpected Node subclass.");
308 }
309 Preconditions.checkState(childCount == 3);
310 boolean funcNeedsParens = (context == Context.START_OF_EXPR);
311 if (funcNeedsParens) {
312 add("(");
313 }
314
315 add("function");
316 add(first);
317
318 add(first.getNext());
319 add(last, Context.PRESERVE_BLOCK);
320 cc.endFunction(context == Context.STATEMENT);
321
322 if (funcNeedsParens) {
323 add(")");
324 }
325 break;
326
327 case Token.GETTER_DEF:
328 case Token.SETTER_DEF:
329 Preconditions.checkState(n.getParent().isObjectLit());
330 Preconditions.checkState(childCount == 1);
331 Preconditions.checkState(first.isFunction());
332
333 // Get methods are unnamed
334 Preconditions.checkState(first.getFirstChild().getString().isEmpty());
335 if (type == Token.GETTER_DEF) {
336 // Get methods have no parameters.
337 Preconditions.checkState(!first.getChildAtIndex(1).hasChildren());
338 add("get ");
339 } else {
340 // Set methods have one parameter.
341 Preconditions.checkState(first.getChildAtIndex(1).hasOneChild());
342 add("set ");
343 }
344
345 // The name is on the GET or SET node.
346 String name = n.getString();
347 Node fn = first;
348 Node parameters = fn.getChildAtIndex(1);
349 Node body = fn.getLastChild();
350
351 // Add the property name.
352 if (!n.isQuotedString() &&
353 TokenStream.isJSIdentifier(name) &&
354 // do not encode literally any non-literal characters that were
355 // Unicode escaped.
356 NodeUtil.isLatin(name)) {
357 add(name);
358 } else {
359 // Determine if the string is a simple number.
360 double d = getSimpleNumber(name);
361 if (!Double.isNaN(d)) {
362 cc.addNumber(d);
363 } else {
364 addJsString(n);
365 }
366 }
367
368 add(parameters);
369 add(body, Context.PRESERVE_BLOCK);
370 break;
371
372 case Token.SCRIPT:
373 case Token.BLOCK: {
374 if (n.getClass() != Node.class) {
375 throw new Error("Unexpected Node subclass.");
376 }
377 boolean preserveBlock = context == Context.PRESERVE_BLOCK;
378 if (preserveBlock) {
379 cc.beginBlock();
380 }
381
382 boolean preferLineBreaks =
383 type == Token.SCRIPT ||
384 (type == Token.BLOCK &&
385 !preserveBlock &&
386 n.getParent() != null &&
387 n.getParent().isScript());
388 for (Node c = first; c != null; c = c.getNext()) {
389 add(c, Context.STATEMENT);
390
391 // VAR doesn't include ';' since it gets used in expressions
392 if (c.isVar()) {
393 cc.endStatement();
394 }
395
396 if (c.isFunction()) {
397 cc.maybeLineBreak();
398 }
399
400 // Prefer to break lines in between top-level statements
401 // because top-level statements are more homogeneous.
402 if (preferLineBreaks) {
403 cc.notePreferredLineBreak();
404 }
405 }
406 if (preserveBlock) {
407 cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
408 }
409 break;
410 }
411
412 case Token.FOR:
413 if (childCount == 4) {
414 add("for(");
415 if (first.isVar()) {
416 add(first, Context.IN_FOR_INIT_CLAUSE);
417 } else {
418 addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE);
419 }
420 add(";");
421 add(first.getNext());
422 add(";");
423 add(first.getNext().getNext());
424 add(")");
425 addNonEmptyStatement(
426 last, getContextForNonEmptyExpression(context), false);
427 } else {
428 Preconditions.checkState(childCount == 3);
429 add("for(");
430 add(first);
431 add("in");
432 add(first.getNext());
433 add(")");
434 addNonEmptyStatement(
435 last, getContextForNonEmptyExpression(context), false);
436 }
437 break;
438
439 case Token.DO:
440 Preconditions.checkState(childCount == 2);
441 add("do");
442 addNonEmptyStatement(first, Context.OTHER, false);
443 add("while(");
444 add(last);
445 add(")");
446 cc.endStatement();
447 break;
448
449 case Token.WHILE:
450 Preconditions.checkState(childCount == 2);
451 add("while(");
452 add(first);
453 add(")");
454 addNonEmptyStatement(
455 last, getContextForNonEmptyExpression(context), false);
456 break;
457
458 case Token.EMPTY:
459 Preconditions.checkState(childCount == 0);
460 break;
461
462 case Token.GETPROP: {
463 Preconditions.checkState(
464 childCount == 2,
465 "Bad GETPROP: expected 2 children, but got %s", childCount);
466 Preconditions.checkState(
467 last.isString(),
468 "Bad GETPROP: RHS should be STRING");
469 boolean needsParens = (first.isNumber());
470 if (needsParens) {
471 add("(");
472 }
473 addExpr(first, NodeUtil.precedence(type), context);
474 if (needsParens) {
475 add(")");
476 }
477 add(".");
478 addIdentifier(last.getString());
479 break;
480 }
481
482 case Token.GETELEM:
483 Preconditions.checkState(
484 childCount == 2,
485 "Bad GETELEM: expected 2 children but got %s", childCount);
486 addExpr(first, NodeUtil.precedence(type), context);
487 add("[");
488 add(first.getNext());
489 add("]");
490 break;
491
492 case Token.WITH:
493 Preconditions.checkState(childCount == 2);
494 add("with(");
495 add(first);
496 add(")");
497 addNonEmptyStatement(
498 last, getContextForNonEmptyExpression(context), false);
499 break;
500
501 case Token.INC:
502 case Token.DEC: {
503 Preconditions.checkState(childCount == 1);
504 String o = type == Token.INC ? "++" : "--";
505 int postProp = n.getIntProp(Node.INCRDECR_PROP);
506 // A non-zero post-prop value indicates a post inc/dec, default of zero
507 // is a pre-inc/dec.
508 if (postProp != 0) {
509 addExpr(first, NodeUtil.precedence(type), context);
510 cc.addOp(o, false);
511 } else {
512 cc.addOp(o, false);
513 add(first);
514 }
515 break;
516 }
517
518 case Token.CALL:
519 // We have two special cases here:
520 // 1) If the left hand side of the call is a direct reference to eval,
521 // then it must have a DIRECT_EVAL annotation. If it does not, then
522 // that means it was originally an indirect call to eval, and that
523 // indirectness must be preserved.
524 // 2) If the left hand side of the call is a property reference,
525 // then the call must not a FREE_CALL annotation. If it does, then
526 // that means it was originally an call without an explicit this and
527 // that must be preserved.
528 if (isIndirectEval(first)
529 || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) {
530 add("(0,");
531 addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER);
532 add(")");
533 } else {
534 addExpr(first, NodeUtil.precedence(type), context);
535 }
536 add("(");
537 addList(first.getNext());
538 add(")");
539 break;
540
541 case Token.IF:
542 boolean hasElse = childCount == 3;
543 boolean ambiguousElseClause =
544 context == Context.BEFORE_DANGLING_ELSE && !hasElse;
545 if (ambiguousElseClause) {
546 cc.beginBlock();
547 }
548
549 add("if(");
550 add(first);
551 add(")");
552
553 if (hasElse) {
554 addNonEmptyStatement(
555 first.getNext(), Context.BEFORE_DANGLING_ELSE, false);
556 add("else");
557 addNonEmptyStatement(
558 last, getContextForNonEmptyExpression(context), false);
559 } else {
560 addNonEmptyStatement(first.getNext(), Context.OTHER, false);
561 Preconditions.checkState(childCount == 2);
562 }
563
564 if (ambiguousElseClause) {
565 cc.endBlock();
566 }
567 break;
568
569 case Token.NULL:
570 Preconditions.checkState(childCount == 0);
571 cc.addConstant("null");
572 break;
573
574 case Token.THIS:
575 Preconditions.checkState(childCount == 0);
576 add("this");
577 break;
578
579 case Token.FALSE:
580 Preconditions.checkState(childCount == 0);
581 cc.addConstant("false");
582 break;
583
584 case Token.TRUE:
585 Preconditions.checkState(childCount == 0);
586 cc.addConstant("true");
587 break;
588
589 case Token.CONTINUE:
590 Preconditions.checkState(childCount <= 1);
591 add("continue");
592 if (childCount == 1) {
593 if (!first.isLabelName()) {
594 throw new Error("Unexpected token type. Should be LABEL_NAME.");
595 }
596 add(" ");
597 add(first);
598 }
599 cc.endStatement();
600 break;
601
602 case Token.DEBUGGER:
603 Preconditions.checkState(childCount == 0);
604 add("debugger");
605 cc.endStatement();
606 break;
607
608 case Token.BREAK:
609 Preconditions.checkState(childCount <= 1);
610 add("break");
611 if (childCount == 1) {
612 if (!first.isLabelName()) {
613 throw new Error("Unexpected token type. Should be LABEL_NAME.");
614 }
615 add(" ");
616 add(first);
617 }
618 cc.endStatement();
619 break;
620
621 case Token.EXPR_RESULT:
622 Preconditions.checkState(childCount == 1);
623 add(first, Context.START_OF_EXPR);
624 cc.endStatement();
625 break;
626
627 case Token.NEW:
628 add("new ");
629 int precedence = NodeUtil.precedence(type);
630
631 // If the first child contains a CALL, then claim higher precedence
632 // to force parentheses. Otherwise, when parsed, NEW will bind to the
633 // first viable parentheses (don't traverse into functions).
634 if (NodeUtil.containsType(
635 first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) {
636 precedence = NodeUtil.precedence(first.getType()) + 1;
637 }
638 addExpr(first, precedence, Context.OTHER);
639
640 // '()' is optional when no arguments are present
641 Node next = first.getNext();
642 if (next != null) {
643 add("(");
644 addList(next);
645 add(")");
646 }
647 break;
648
649 case Token.STRING_KEY:
650 Preconditions.checkState(
651 childCount == 1, "Object lit key must have 1 child");
652 addJsString(n);
653 break;
654
655 case Token.STRING:
656 Preconditions.checkState(
657 childCount == 0, "A string may not have children");
658 addJsString(n);
659 break;
660
661 case Token.DELPROP:
662 Preconditions.checkState(childCount == 1);
663 add("delete ");
664 add(first);
665 break;
666
667 case Token.OBJECTLIT: {
668 boolean needsParens = (context == Context.START_OF_EXPR);
669 if (needsParens) {
670 add("(");
671 }
672 add("{");
673 for (Node c = first; c != null; c = c.getNext()) {
674 if (c != first) {
675 cc.listSeparator();
676 }
677
678 if (c.isGetterDef() || c.isSetterDef()) {
679 add(c);
680 } else {
681 Preconditions.checkState(c.isStringKey());
682 String key = c.getString();
683 // Object literal property names don't have to be quoted if they
684 // are not JavaScript keywords
685 if (!c.isQuotedString() &&
686 !TokenStream.isKeyword(key) &&
687 TokenStream.isJSIdentifier(key) &&
688 // do not encode literally any non-literal characters that
689 // were Unicode escaped.
690 NodeUtil.isLatin(key)) {
691 add(key);
692 } else {
693 // Determine if the string is a simple number.
694 double d = getSimpleNumber(key);
695 if (!Double.isNaN(d)) {
696 cc.addNumber(d);
697 } else {
698 addExpr(c, 1, Context.OTHER);
699 }
700 }
701 add(":");
702 addExpr(c.getFirstChild(), 1, Context.OTHER);
703 }
704 }
705 add("}");
706 if (needsParens) {
707 add(")");
708 }
709 break;
710 }
711
712 case Token.SWITCH:
713 add("switch(");
714 add(first);
715 add(")");
716 cc.beginBlock();
717 addAllSiblings(first.getNext());
718 cc.endBlock(context == Context.STATEMENT);
719 break;
720
721 case Token.CASE:
722 Preconditions.checkState(childCount == 2);
723 add("case ");
724 add(first);
725 addCaseBody(last);
726 break;
727
728 case Token.DEFAULT_CASE:
729 Preconditions.checkState(childCount == 1);
730 add("default");
731 addCaseBody(first);
732 break;
733
734 case Token.LABEL:
735 Preconditions.checkState(childCount == 2);
736 if (!first.isLabelName()) {
737 throw new Error("Unexpected token type. Should be LABEL_NAME.");
738 }
739 add(first);
740 add(":");
741 addNonEmptyStatement(
742 last, getContextForNonEmptyExpression(context), true);
743 break;
744
745 case Token.CAST:
746 add("(");
747 add(first);
748 add(")");
749 break;
750
751 default:
752 throw new Error("Unknown type " + type + "\n" + n.toStringTree());
753 }
754
755 cc.endSourceMapping(n);
756 }
757
758 /**
759 * We could use addList recursively here, but sometimes we produce
760 * very deeply nested operators and run out of stack space, so we
761 * just unroll the recursion when possible.
762 *
763 * We assume nodes are left-recursive.
764 */
765 private void unrollBinaryOperator(
766 Node n, int op, String opStr, Context context,
767 Context rhsContext, int leftPrecedence, int rightPrecedence) {
768 Node firstNonOperator = n.getFirstChild();
769 while (firstNonOperator.getType() == op) {
770 firstNonOperator = firstNonOperator.getFirstChild();
771 }
772
773 addExpr(firstNonOperator, leftPrecedence, context);
774
775 Node current = firstNonOperator;
776 do {
777 current = current.getParent();
778 cc.addOp(opStr, true);
779 addExpr(current.getFirstChild().getNext(), rightPrecedence, rhsContext);
780 } while (current != n);
781 }
782
783 static boolean isSimpleNumber(String s) {
784 int len = s.length();
785 for (int index = 0; index < len; index++) {
786 char c = s.charAt(index);
787 if (c < '0' || c > '9') {
788 return false;
789 }
790 }
791 return len > 0 && s.charAt(0) != '0';
792 }
793
794 static double getSimpleNumber(String s) {
795 if (isSimpleNumber(s)) {
796 try {
797 long l = Long.parseLong(s);
798 if (l < NodeUtil.MAX_POSITIVE_INTEGER_NUMBER) {
799 return l;
800 }
801 } catch (NumberFormatException e) {
802 // The number was too long to parse. Fall through to NaN.
803 }
804 }
805 return Double.NaN;
806 }
807
808 /**
809 * @return Whether the name is an indirect eval.
810 */
811 private boolean isIndirectEval(Node n) {
812 return n.isName() && "eval".equals(n.getString()) &&
813 !n.getBooleanProp(Node.DIRECT_EVAL);
814 }
815
816 /**
817 * Adds a block or expression, substituting a VOID with an empty statement.
818 * This is used for "for (...);" and "if (...);" type statements.
819 *
820 * @param n The node to print.
821 * @param context The context to determine how the node should be printed.
822 */
823 private void addNonEmptyStatement(
824 Node n, Context context, boolean allowNonBlockChild) {
825 Node nodeToProcess = n;
826
827 if (!allowNonBlockChild && !n.isBlock()) {
828 throw new Error("Missing BLOCK child.");
829 }
830
831 // Strip unneeded blocks, that is blocks with <2 children unless
832 // the CodePrinter specifically wants to keep them.
833 if (n.isBlock()) {
834 int count = getNonEmptyChildCount(n, 2);
835 if (count == 0) {
836 if (cc.shouldPreserveExtraBlocks()) {
837 cc.beginBlock();
838 cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
839 } else {
840 cc.endStatement(true);
841 }
842 return;
843 }
844
845 if (count == 1) {
846 // Hack around a couple of browser bugs:
847 // Safari needs a block around function declarations.
848 // IE6/7 needs a block around DOs.
849 Node firstAndOnlyChild = getFirstNonEmptyChild(n);
850 boolean alwaysWrapInBlock = cc.shouldPreserveExtraBlocks();
851 if (alwaysWrapInBlock || isOneExactlyFunctionOrDo(firstAndOnlyChild)) {
852 cc.beginBlock();
853 add(firstAndOnlyChild, Context.STATEMENT);
854 cc.maybeLineBreak();
855 cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
856 return;
857 } else {
858 // Continue with the only child.
859 nodeToProcess = firstAndOnlyChild;
860 }
861 }
862
863 if (count > 1) {
864 context = Context.PRESERVE_BLOCK;
865 }
866 }
867
868 if (nodeToProcess.isEmpty()) {
869 cc.endStatement(true);
870 } else {
871 add(nodeToProcess, context);
872
873 // VAR doesn't include ';' since it gets used in expressions - so any
874 // VAR in a statement context needs a call to endStatement() here.
875 if (nodeToProcess.isVar()) {
876 cc.endStatement();
877 }
878 }
879 }
880
881 /**
882 * @return Whether the Node is a DO or FUNCTION (with or without
883 * labels).
884 */
885 private boolean isOneExactlyFunctionOrDo(Node n) {
886 if (n.isLabel()) {
887 Node labeledStatement = n.getLastChild();
888 if (!labeledStatement.isBlock()) {
889 return isOneExactlyFunctionOrDo(labeledStatement);
890 } else {
891 // For labels with block children, we need to ensure that a
892 // labeled FUNCTION or DO isn't generated when extraneous BLOCKs
893 // are skipped.
894 if (getNonEmptyChildCount(n, 2) == 1) {
895 return isOneExactlyFunctionOrDo(getFirstNonEmptyChild(n));
896 } else {
897 // Either a empty statement or an block with more than one child,
898 // way it isn't a FUNCTION or DO.
899 return false;
900 }
901 }
902 } else {
903 return (n.isFunction() || n.isDo());
904 }
905 }
906
907 private void addExpr(Node n, int minPrecedence, Context context) {
908 if ((NodeUtil.precedence(n.getType()) < minPrecedence) ||
909 ((context == Context.IN_FOR_INIT_CLAUSE) && n.isIn())){
910 add("(");
911 add(n, Context.OTHER);
912 add(")");
913 } else {
914 add(n, context);
915 }
916 }
917
918 void addList(Node firstInList) {
919 addList(firstInList, true, Context.OTHER);
920 }
921
922 void addList(Node firstInList, boolean isArrayOrFunctionArgument) {
923 addList(firstInList, isArrayOrFunctionArgument, Context.OTHER);
924 }
925
926 void addList(Node firstInList, boolean isArrayOrFunctionArgument,
927 Context lhsContext) {
928 for (Node n = firstInList; n != null; n = n.getNext()) {
929 boolean isFirst = n == firstInList;
930 if (isFirst) {
931 addExpr(n, isArrayOrFunctionArgument ? 1 : 0, lhsContext);
932 } else {
933 cc.listSeparator();
934 addExpr(n, isArrayOrFunctionArgument ? 1 : 0, Context.OTHER);
935 }
936 }
937 }
938
939 /**
940 * This function adds a comma-separated list as is specified by an ARRAYLIT
941 * node with the associated skipIndexes array. This is a space optimization
942 * since we avoid creating a whole Node object for each empty array literal
943 * slot.
944 * @param firstInList The first in the node list (chained through the next
945 * property).
946 */
947 void addArrayList(Node firstInList) {
948 boolean lastWasEmpty = false;
949 for (Node n = firstInList; n != null; n = n.getNext()) {
950 if (n != firstInList) {
951 cc.listSeparator();
952 }
953 addExpr(n, 1, Context.OTHER);
954 lastWasEmpty = n.isEmpty();
955 }
956
957 if (lastWasEmpty) {
958 cc.listSeparator();
959 }
960 }
961
962 void addCaseBody(Node caseBody) {
963 cc.beginCaseBody();
964 add(caseBody);
965 cc.endCaseBody();
966 }
967
968 void addAllSiblings(Node n) {
969 for (Node c = n; c != null; c = c.getNext()) {
970 add(c);
971 }
972 }
973
974 /** Outputs a JS string, using the optimal (single/double) quote character */
975 private void addJsString(Node n) {
976 String s = n.getString();
977 boolean useSlashV = n.getBooleanProp(Node.SLASH_V);
978 if (useSlashV) {
979 add(jsString(n.getString(), useSlashV));
980 } else {
981 String cached = ESCAPED_JS_STRINGS.get(s);
982 if (cached == null) {
983 cached = jsString(n.getString(), useSlashV);
984 ESCAPED_JS_STRINGS.put(s, cached);
985 }
986 add(cached);
987 }
988 }
989
990 private String jsString(String s, boolean useSlashV) {
991 int singleq = 0, doubleq = 0;
992
993 // could count the quotes and pick the optimal quote character
994 for (int i = 0; i < s.length(); i++) {
995 switch (s.charAt(i)) {
996 case '"': doubleq++; break;
997 case '\'': singleq++; break;
998 }
999 }
1000
1001 String doublequote, singlequote;
1002 char quote;
1003 if (preferSingleQuotes ?
1004 (singleq <= doubleq) : (singleq < doubleq)) {
1005 // more double quotes so enclose in single quotes.
1006 quote = '\'';
1007 doublequote = "\"";
1008 singlequote = "\\\'";
1009 } else {
1010 // more single quotes so escape the doubles
1011 quote = '\"';
1012 doublequote = "\\\"";
1013 singlequote = "\'";
1014 }
1015
1016 return strEscape(s, quote, doublequote, singlequote, "\\\\",
1017 outputCharsetEncoder, useSlashV, false);
1018 }
1019
1020 /** Escapes regular expression */
1021 String regexpEscape(String s, CharsetEncoder outputCharsetEncoder) {
1022 return strEscape(s, '/', "\"", "'", "\\", outputCharsetEncoder, false, true);
1023 }
1024
1025 /**
1026 * Escapes the given string to a double quoted (") JavaScript/JSON string
1027 */
1028 String escapeToDoubleQuotedJsString(String s) {
1029 return strEscape(s, '"', "\\\"", "\'", "\\\\", null, false, false);
1030 }
1031
1032 /* If the user doesn't want to specify an output charset encoder, assume
1033 they want Latin/ASCII characters only.
1034 */
1035 String regexpEscape(String s) {
1036 return regexpEscape(s, null);
1037 }
1038
1039 /** Helper to escape JavaScript string as well as regular expression */
1040 private String strEscape(
1041 String s,
1042 char quote,
1043 String doublequoteEscape,
1044 String singlequoteEscape,
1045 String backslashEscape,
1046 CharsetEncoder outputCharsetEncoder,
1047 boolean useSlashV,
1048 boolean isRegexp) {
1049 StringBuilder sb = new StringBuilder(s.length() + 2);
1050 sb.append(quote);
1051 for (int i = 0; i < s.length(); i++) {
1052 char c = s.charAt(i);
1053 switch (c) {
1054 case '\0': sb.append("\\x00"); break;
1055 case '\u000B':
1056 if (useSlashV) {
1057 sb.append("\\v");
1058 } else {
1059 sb.append("\\x0B");
1060 }
1061 break;
1062 // From the SingleEscapeCharacter grammar production.
1063 case '\b': sb.append("\\b"); break;
1064 case '\f': sb.append("\\f"); break;
1065 case '\n': sb.append("\\n"); break;
1066 case '\r': sb.append("\\r"); break;
1067 case '\t': sb.append("\\t"); break;
1068 case '\\': sb.append(backslashEscape); break;
1069 case '\"': sb.append(doublequoteEscape); break;
1070 case '\'': sb.append(singlequoteEscape); break;
1071
1072 // From LineTerminators (ES5 Section 7.3, Table 3)
1073 case '\u2028': sb.append("\\u2028"); break;
1074 case '\u2029': sb.append("\\u2029"); break;
1075
1076 case '=':
1077 // '=' is a syntactically signficant regexp character.
1078 if (trustedStrings || isRegexp) {
1079 sb.append(c);
1080 } else {
1081 sb.append("\\x3d");
1082 }
1083 break;
1084
1085 case '&':
1086 if (trustedStrings || isRegexp) {
1087 sb.append(c);
1088 } else {
1089 sb.append("\\x26");
1090 }
1091 break;
1092
1093 case '>':
1094 if (!trustedStrings && !isRegexp) {
1095 sb.append(GT_ESCAPED);
1096 break;
1097 }
1098
1099 // Break --> into --\> or ]]> into ]]\>
1100 //
1101 // This is just to prevent developers from shooting themselves in the
1102 // foot, and does not provide the level of security that you get
1103 // with trustedString == false.
1104 if (i >= 2 &&
1105 ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||
1106 (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {
1107 sb.append(GT_ESCAPED);
1108 } else {
1109 sb.append(c);
1110 }
1111 break;
1112 case '<':
1113 if (!trustedStrings && !isRegexp) {
1114 sb.append(LT_ESCAPED);
1115 break;
1116 }
1117
1118 // Break </script into <\/script
1119 // As above, this is just to prevent developers from doing this
1120 // accidentally.
1121 final String END_SCRIPT = "/script";
1122
1123 // Break <!-- into <\!--
1124 final String START_COMMENT = "!--";
1125
1126 if (s.regionMatches(true, i + 1, END_SCRIPT, 0,
1127 END_SCRIPT.length())) {
1128 sb.append(LT_ESCAPED);
1129 } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,
1130 START_COMMENT.length())) {
1131 sb.append(LT_ESCAPED);
1132 } else {
1133 sb.append(c);
1134 }
1135 break;
1136 default:
1137 // If we're given an outputCharsetEncoder, then check if the
1138 // character can be represented in this character set.
1139 if (outputCharsetEncoder != null) {
1140 if (outputCharsetEncoder.canEncode(c)) {
1141 sb.append(c);
1142 } else {
1143 // Unicode-escape the character.
1144 appendHexJavaScriptRepresentation(sb, c);
1145 }
1146 } else {
1147 // No charsetEncoder provided - pass straight Latin characters
1148 // through, and escape the rest. Doing the explicit character
1149 // check is measurably faster than using the CharsetEncoder.
1150 if (c > 0x1f && c < 0x7f) {
1151 sb.append(c);
1152 } else {
1153 // Other characters can be misinterpreted by some JS parsers,
1154 // or perhaps mangled by proxies along the way,
1155 // so we play it safe and Unicode escape them.
1156 appendHexJavaScriptRepresentation(sb, c);
1157 }
1158 }
1159 }
1160 }
1161 sb.append(quote);
1162 return sb.toString();
1163 }
1164
1165 static String identifierEscape(String s) {
1166 // First check if escaping is needed at all -- in most cases it isn't.
1167 if (NodeUtil.isLatin(s)) {
1168 return s;
1169 }
1170
1171 // Now going through the string to escape non-Latin characters if needed.
1172 StringBuilder sb = new StringBuilder();
1173 for (int i = 0; i < s.length(); i++) {
1174 char c = s.charAt(i);
1175 // Identifiers should always go to Latin1/ ASCII characters because
1176 // different browser's rules for valid identifier characters are
1177 // crazy.
1178 if (c > 0x1F && c < 0x7F) {
1179 sb.append(c);
1180 } else {
1181 appendHexJavaScriptRepresentation(sb, c);
1182 }
1183 }
1184 return sb.toString();
1185 }
1186 /**
1187 * @param maxCount The maximum number of children to look for.
1188 * @return The number of children of this node that are non empty up to
1189 * maxCount.
1190 */
1191 private static int getNonEmptyChildCount(Node n, int maxCount) {
1192 int i = 0;
1193 Node c = n.getFirstChild();
1194 for (; c != null && i < maxCount; c = c.getNext()) {
1195 if (c.isBlock()) {
1196 i += getNonEmptyChildCount(c, maxCount-i);
1197 } else if (!c.isEmpty()) {
1198 i++;
1199 }
1200 }
1201 return i;
1202 }
1203
1204 /** Gets the first non-empty child of the given node. */
1205 private static Node getFirstNonEmptyChild(Node n) {
1206 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
1207 if (c.isBlock()) {
1208 Node result = getFirstNonEmptyChild(c);
1209 if (result != null) {
1210 return result;
1211 }
1212 } else if (!c.isEmpty()) {
1213 return c;
1214 }
1215 }
1216 return null;
1217 }
1218
1219 // Information on the current context. Used for disambiguating special cases.
1220 // For example, a "{" could indicate the start of an object literal or a
1221 // block, depending on the current context.
1222 enum Context {
1223 STATEMENT,
1224 BEFORE_DANGLING_ELSE, // a hack to resolve the else-clause ambiguity
1225 START_OF_EXPR,
1226 PRESERVE_BLOCK,
1227 // Are we inside the init clause of a for loop? If so, the containing
1228 // expression can't contain an in operator. Pass this context flag down
1229 // until we reach expressions which no longer have the limitation.
1230 IN_FOR_INIT_CLAUSE,
1231 OTHER
1232 }
1233
1234 private Context getContextForNonEmptyExpression(Context currentContext) {
1235 return currentContext == Context.BEFORE_DANGLING_ELSE ?
1236 Context.BEFORE_DANGLING_ELSE : Context.OTHER;
1237 }
1238
1239 /**
1240 * If we're in a IN_FOR_INIT_CLAUSE, we can't permit in operators in the
1241 * expression. Pass on the IN_FOR_INIT_CLAUSE flag through subexpressions.
1242 */
1243 private Context getContextForNoInOperator(Context context) {
1244 return (context == Context.IN_FOR_INIT_CLAUSE
1245 ? Context.IN_FOR_INIT_CLAUSE : Context.OTHER);
1246 }
1247
1248 /**
1249 * @see #appendHexJavaScriptRepresentation(int, Appendable)
1250 */
1251 private static void appendHexJavaScriptRepresentation(
1252 StringBuilder sb, char c) {
1253 try {
1254 appendHexJavaScriptRepresentation(c, sb);
1255 } catch (IOException ex) {
1256 // StringBuilder does not throw IOException.
1257 throw new RuntimeException(ex);
1258 }
1259 }
1260
1261 /**
1262 * Returns a JavaScript representation of the character in a hex escaped
1263 * format.
1264 *
1265 * @param codePoint The code point to append.
1266 * @param out The buffer to which the hex representation should be appended.
1267 */
1268 private static void appendHexJavaScriptRepresentation(
1269 int codePoint, Appendable out)
1270 throws IOException {
1271 if (Character.isSupplementaryCodePoint(codePoint)) {
1272 // Handle supplementary Unicode values which are not representable in
1273 // JavaScript. We deal with these by escaping them as two 4B sequences
1274 // so that they will round-trip properly when sent from Java to JavaScript
1275 // and back.
1276 char[] surrogates = Character.toChars(codePoint);
1277 appendHexJavaScriptRepresentation(surrogates[0], out);
1278 appendHexJavaScriptRepresentation(surrogates[1], out);
1279 return;
1280 }
1281 out.append("\\u")
1282 .append(HEX_CHARS[(codePoint >>> 12) & 0xf])
1283 .append(HEX_CHARS[(codePoint >>> 8) & 0xf])
1284 .append(HEX_CHARS[(codePoint >>> 4) & 0xf])
1285 .append(HEX_CHARS[codePoint & 0xf]);
1286 }
1287 }