Debian Codegraph @

rhino/src/org/mozilla/javascript/Decompiler.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript;
8
9 import org.mozilla.javascript.ast.FunctionNode;
10
11 /**
12 * The following class save decompilation information about the source.
13 * Source information is returned from the parser as a String
14 * associated with function nodes and with the toplevel script. When
15 * saved in the constant pool of a class, this string will be UTF-8
16 * encoded, and token values will occupy a single byte.
17
18 * Source is saved (mostly) as token numbers. The tokens saved pretty
19 * much correspond to the token stream of a 'canonical' representation
20 * of the input program, as directed by the parser. (There were a few
21 * cases where tokens could have been left out where decompiler could
22 * easily reconstruct them, but I left them in for clarity). (I also
23 * looked adding source collection to TokenStream instead, where I
24 * could have limited the changes to a few lines in getToken... but
25 * this wouldn't have saved any space in the resulting source
26 * representation, and would have meant that I'd have to duplicate
27 * parser logic in the decompiler to disambiguate situations where
28 * newlines are important.) The function decompile expands the
29 * tokens back into their string representations, using simple
30 * lookahead to correct spacing and indentation.
31 *
32 * Assignments are saved as two-token pairs (Token.ASSIGN, op). Number tokens
33 * are stored inline, as a NUMBER token, a character representing the type, and
34 * either 1 or 4 characters representing the bit-encoding of the number. String
35 * types NAME, STRING and OBJECT are currently stored as a token type,
36 * followed by a character giving the length of the string (assumed to
37 * be less than 2^16), followed by the characters of the string
38 * inlined into the source string. Changing this to some reference to
39 * to the string in the compiled class' constant pool would probably
40 * save a lot of space... but would require some method of deriving
41 * the final constant pool entry from information available at parse
42 * time.
43 */
44 public class Decompiler
45 {
46 /**
47 * Flag to indicate that the decompilation should omit the
48 * function header and trailing brace.
49 */
50 public static final int ONLY_BODY_FLAG = 1 << 0;
51
52 /**
53 * Flag to indicate that the decompilation generates toSource result.
54 */
55 public static final int TO_SOURCE_FLAG = 1 << 1;
56
57 /**
58 * Decompilation property to specify initial ident value.
59 */
60 public static final int INITIAL_INDENT_PROP = 1;
61
62 /**
63 * Decompilation property to specify default identation offset.
64 */
65 public static final int INDENT_GAP_PROP = 2;
66
67 /**
68 * Decompilation property to specify identation offset for case labels.
69 */
70 public static final int CASE_GAP_PROP = 3;
71
72 // Marker to denote the last RC of function so it can be distinguished from
73 // the last RC of object literals in case of function expressions
74 private static final int FUNCTION_END = Token.LAST_TOKEN + 1;
75
76 String getEncodedSource()
77 {
78 return sourceToString(0);
79 }
80
81 int getCurrentOffset()
82 {
83 return sourceTop;
84 }
85
86 int markFunctionStart(int functionType)
87 {
88 int savedOffset = getCurrentOffset();
89 if (functionType != FunctionNode.ARROW_FUNCTION) {
90 addToken(Token.FUNCTION);
91 append((char)functionType);
92 }
93 return savedOffset;
94 }
95
96 int markFunctionEnd(int functionStart)
97 {
98 int offset = getCurrentOffset();
99 append((char)FUNCTION_END);
100 return offset;
101 }
102
103 void addToken(int token)
104 {
105 if (!(0 <= token && token <= Token.LAST_TOKEN))
106 throw new IllegalArgumentException();
107
108 append((char)token);
109 }
110
111 void addEOL(int token)
112 {
113 if (!(0 <= token && token <= Token.LAST_TOKEN))
114 throw new IllegalArgumentException();
115
116 append((char)token);
117 append((char)Token.EOL);
118 }
119
120 void addName(String str)
121 {
122 addToken(Token.NAME);
123 appendString(str);
124 }
125
126 void addString(String str)
127 {
128 addToken(Token.STRING);
129 appendString(str);
130 }
131
132 void addRegexp(String regexp, String flags)
133 {
134 addToken(Token.REGEXP);
135 appendString('/' + regexp + '/' + flags);
136 }
137
138 void addNumber(double n)
139 {
140 addToken(Token.NUMBER);
141
142 /* encode the number in the source stream.
143 * Save as NUMBER type (char | char char char char)
144 * where type is
145 * 'D' - double, 'S' - short, 'J' - long.
146
147 * We need to retain float vs. integer type info to keep the
148 * behavior of liveconnect type-guessing the same after
149 * decompilation. (Liveconnect tries to present 1.0 to Java
150 * as a float/double)
151 * OPT: This is no longer true. We could compress the format.
152
153 * This may not be the most space-efficient encoding;
154 * the chars created below may take up to 3 bytes in
155 * constant pool UTF-8 encoding, so a Double could take
156 * up to 12 bytes.
157 */
158
159 long lbits = (long)n;
160 if (lbits != n) {
161 // if it's floating point, save as a Double bit pattern.
162 // (12/15/97 our scanner only returns Double for f.p.)
163 lbits = Double.doubleToLongBits(n);
164 append('D');
165 append((char)(lbits >> 48));
166 append((char)(lbits >> 32));
167 append((char)(lbits >> 16));
168 append((char)lbits);
169 }
170 else {
171 // we can ignore negative values, bc they're already prefixed
172 // by NEG
173 if (lbits < 0) Kit.codeBug();
174
175 // will it fit in a char?
176 // this gives a short encoding for integer values up to 2^16.
177 if (lbits <= Character.MAX_VALUE) {
178 append('S');
179 append((char)lbits);
180 }
181 else { // Integral, but won't fit in a char. Store as a long.
182 append('J');
183 append((char)(lbits >> 48));
184 append((char)(lbits >> 32));
185 append((char)(lbits >> 16));
186 append((char)lbits);
187 }
188 }
189 }
190
191 private void appendString(String str)
192 {
193 int L = str.length();
194 int lengthEncodingSize = 1;
195 if (L >= 0x8000) {
196 lengthEncodingSize = 2;
197 }
198 int nextTop = sourceTop + lengthEncodingSize + L;
199 if (nextTop > sourceBuffer.length) {
200 increaseSourceCapacity(nextTop);
201 }
202 if (L >= 0x8000) {
203 // Use 2 chars to encode strings exceeding 32K, were the highest
204 // bit in the first char indicates presence of the next byte
205 sourceBuffer[sourceTop] = (char)(0x8000 | (L >>> 16));
206 ++sourceTop;
207 }
208 sourceBuffer[sourceTop] = (char)L;
209 ++sourceTop;
210 str.getChars(0, L, sourceBuffer, sourceTop);
211 sourceTop = nextTop;
212 }
213
214 private void append(char c)
215 {
216 if (sourceTop == sourceBuffer.length) {
217 increaseSourceCapacity(sourceTop + 1);
218 }
219 sourceBuffer[sourceTop] = c;
220 ++sourceTop;
221 }
222
223 private void increaseSourceCapacity(int minimalCapacity)
224 {
225 // Call this only when capacity increase is must
226 if (minimalCapacity <= sourceBuffer.length) Kit.codeBug();
227 int newCapacity = sourceBuffer.length * 2;
228 if (newCapacity < minimalCapacity) {
229 newCapacity = minimalCapacity;
230 }
231 char[] tmp = new char[newCapacity];
232 System.arraycopy(sourceBuffer, 0, tmp, 0, sourceTop);
233 sourceBuffer = tmp;
234 }
235
236 private String sourceToString(int offset)
237 {
238 if (offset < 0 || sourceTop < offset) Kit.codeBug();
239 return new String(sourceBuffer, offset, sourceTop - offset);
240 }
241
242 /**
243 * Decompile the source information associated with this js
244 * function/script back into a string. For the most part, this
245 * just means translating tokens back to their string
246 * representations; there's a little bit of lookahead logic to
247 * decide the proper spacing/indentation. Most of the work in
248 * mapping the original source to the prettyprinted decompiled
249 * version is done by the parser.
250 *
251 * @param source encoded source tree presentation
252 *
253 * @param flags flags to select output format
254 *
255 * @param properties indentation properties
256 *
257 */
258 public static String decompile(String source, int flags,
259 UintMap properties)
260 {
261 int length = source.length();
262 if (length == 0) { return ""; }
263
264 int indent = properties.getInt(INITIAL_INDENT_PROP, 0);
265 if (indent < 0) throw new IllegalArgumentException();
266 int indentGap = properties.getInt(INDENT_GAP_PROP, 4);
267 if (indentGap < 0) throw new IllegalArgumentException();
268 int caseGap = properties.getInt(CASE_GAP_PROP, 2);
269 if (caseGap < 0) throw new IllegalArgumentException();
270
271 StringBuilder result = new StringBuilder();
272 boolean justFunctionBody = (0 != (flags & Decompiler.ONLY_BODY_FLAG));
273 boolean toSource = (0 != (flags & Decompiler.TO_SOURCE_FLAG));
274
275 // Spew tokens in source, for debugging.
276 // as TYPE number char
277 if (printSource) {
278 System.err.println("length:" + length);
279 for (int i = 0; i < length; ++i) {
280 // Note that tokenToName will fail unless Context.printTrees
281 // is true.
282 String tokenname = null;
283 if (Token.printNames) {
284 tokenname = Token.name(source.charAt(i));
285 }
286 if (tokenname == null) {
287 tokenname = "---";
288 }
289 String pad = tokenname.length() > 7
290 ? "\t"
291 : "\t\t";
292 System.err.println
293 (tokenname
294 + pad + (int)source.charAt(i)
295 + "\t'" + ScriptRuntime.escapeString
296 (source.substring(i, i+1))
297 + "'");
298 }
299 System.err.println();
300 }
301
302 int braceNesting = 0;
303 boolean afterFirstEOL = false;
304 int i = 0;
305 int topFunctionType;
306 if (source.charAt(i) == Token.SCRIPT) {
307 ++i;
308 topFunctionType = -1;
309 } else {
310 topFunctionType = source.charAt(i + 1);
311 }
312
313 if (!toSource) {
314 // add an initial newline to exactly match js.
315 result.append('\n');
316 for (int j = 0; j < indent; j++)
317 result.append(' ');
318 } else {
319 if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) {
320 result.append('(');
321 }
322 }
323
324 while (i < length) {
325 switch(source.charAt(i)) {
326 case Token.GET:
327 case Token.SET:
328 case Token.METHOD:
329 if (source.charAt(i) == Token.GET) {
330 result.append("get ");
331 } else if (source.charAt(i) == Token.SET) {
332 result.append("set ");
333 }
334 ++i;
335 i = printSourceString(source, i + 1, false, result);
336 // Now increment one more to get past the FUNCTION token
337 ++i;
338 break;
339
340 case Token.NAME:
341 case Token.REGEXP: // re-wrapped in '/'s in parser...
342 i = printSourceString(source, i + 1, false, result);
343 continue;
344
345 case Token.STRING:
346 i = printSourceString(source, i + 1, true, result);
347 continue;
348
349 case Token.NUMBER:
350 i = printSourceNumber(source, i + 1, result);
351 continue;
352
353 case Token.TRUE:
354 result.append("true");
355 break;
356
357 case Token.FALSE:
358 result.append("false");
359 break;
360
361 case Token.NULL:
362 result.append("null");
363 break;
364
365 case Token.THIS:
366 result.append("this");
367 break;
368
369 case Token.FUNCTION:
370 ++i; // skip function type
371 result.append("function ");
372 break;
373
374 case FUNCTION_END:
375 // Do nothing
376 break;
377
378 case Token.COMMA:
379 result.append(", ");
380 break;
381
382 case Token.LC:
383 ++braceNesting;
384 if (Token.EOL == getNext(source, length, i))
385 indent += indentGap;
386 result.append('{');
387 break;
388
389 case Token.RC: {
390 --braceNesting;
391 /* don't print the closing RC if it closes the
392 * toplevel function and we're called from
393 * decompileFunctionBody.
394 */
395 if (justFunctionBody && braceNesting == 0)
396 break;
397
398 result.append('}');
399 switch (getNext(source, length, i)) {
400 case Token.EOL:
401 case FUNCTION_END:
402 indent -= indentGap;
403 break;
404 case Token.WHILE:
405 case Token.ELSE:
406 indent -= indentGap;
407 result.append(' ');
408 break;
409 }
410 break;
411 }
412 case Token.LP:
413 result.append('(');
414 break;
415
416 case Token.RP:
417 result.append(')');
418 if (Token.LC == getNext(source, length, i))
419 result.append(' ');
420 break;
421
422 case Token.LB:
423 result.append('[');
424 break;
425
426 case Token.RB:
427 result.append(']');
428 break;
429
430 case Token.EOL: {
431 if (toSource) break;
432 boolean newLine = true;
433 if (!afterFirstEOL) {
434 afterFirstEOL = true;
435 if (justFunctionBody) {
436 /* throw away just added 'function name(...) {'
437 * and restore the original indent
438 */
439 result.setLength(0);
440 indent -= indentGap;
441 newLine = false;
442 }
443 }
444 if (newLine) {
445 result.append('\n');
446 }
447
448 /* add indent if any tokens remain,
449 * less setback if next token is
450 * a label, case or default.
451 */
452 if (i + 1 < length) {
453 int less = 0;
454 int nextToken = source.charAt(i + 1);
455 if (nextToken == Token.CASE
456 || nextToken == Token.DEFAULT)
457 {
458 less = indentGap - caseGap;
459 } else if (nextToken == Token.RC) {
460 less = indentGap;
461 }
462
463 /* elaborate check against label... skip past a
464 * following inlined NAME and look for a COLON.
465 */
466 else if (nextToken == Token.NAME) {
467 int afterName = getSourceStringEnd(source, i + 2);
468 if (source.charAt(afterName) == Token.COLON)
469 less = indentGap;
470 }
471
472 for (; less < indent; less++)
473 result.append(' ');
474 }
475 break;
476 }
477 case Token.DOT:
478 result.append('.');
479 break;
480
481 case Token.NEW:
482 result.append("new ");
483 break;
484
485 case Token.DELPROP:
486 result.append("delete ");
487 break;
488
489 case Token.IF:
490 result.append("if ");
491 break;
492
493 case Token.ELSE:
494 result.append("else ");
495 break;
496
497 case Token.FOR:
498 result.append("for ");
499 break;
500
501 case Token.IN:
502 result.append(" in ");
503 break;
504
505 case Token.WITH:
506 result.append("with ");
507 break;
508
509 case Token.WHILE:
510 result.append("while ");
511 break;
512
513 case Token.DO:
514 result.append("do ");
515 break;
516
517 case Token.TRY:
518 result.append("try ");
519 break;
520
521 case Token.CATCH:
522 result.append("catch ");
523 break;
524
525 case Token.FINALLY:
526 result.append("finally ");
527 break;
528
529 case Token.THROW:
530 result.append("throw ");
531 break;
532
533 case Token.SWITCH:
534 result.append("switch ");
535 break;
536
537 case Token.BREAK:
538 result.append("break");
539 if (Token.NAME == getNext(source, length, i))
540 result.append(' ');
541 break;
542
543 case Token.CONTINUE:
544 result.append("continue");
545 if (Token.NAME == getNext(source, length, i))
546 result.append(' ');
547 break;
548
549 case Token.CASE:
550 result.append("case ");
551 break;
552
553 case Token.DEFAULT:
554 result.append("default");
555 break;
556
557 case Token.RETURN:
558 result.append("return");
559 if (Token.SEMI != getNext(source, length, i))
560 result.append(' ');
561 break;
562
563 case Token.VAR:
564 result.append("var ");
565 break;
566
567 case Token.LET:
568 result.append("let ");
569 break;
570
571 case Token.SEMI:
572 result.append(';');
573 if (Token.EOL != getNext(source, length, i)) {
574 // separators in FOR
575 result.append(' ');
576 }
577 break;
578
579 case Token.ASSIGN:
580 result.append(" = ");
581 break;
582
583 case Token.ASSIGN_ADD:
584 result.append(" += ");
585 break;
586
587 case Token.ASSIGN_SUB:
588 result.append(" -= ");
589 break;
590
591 case Token.ASSIGN_MUL:
592 result.append(" *= ");
593 break;
594
595 case Token.ASSIGN_DIV:
596 result.append(" /= ");
597 break;
598
599 case Token.ASSIGN_MOD:
600 result.append(" %= ");
601 break;
602
603 case Token.ASSIGN_BITOR:
604 result.append(" |= ");
605 break;
606
607 case Token.ASSIGN_BITXOR:
608 result.append(" ^= ");
609 break;
610
611 case Token.ASSIGN_BITAND:
612 result.append(" &= ");
613 break;
614
615 case Token.ASSIGN_LSH:
616 result.append(" <<= ");
617 break;
618
619 case Token.ASSIGN_RSH:
620 result.append(" >>= ");
621 break;
622
623 case Token.ASSIGN_URSH:
624 result.append(" >>>= ");
625 break;
626
627 case Token.HOOK:
628 result.append(" ? ");
629 break;
630
631 case Token.OBJECTLIT:
632 // pun OBJECTLIT to mean colon in objlit property
633 // initialization.
634 // This needs to be distinct from COLON in the general case
635 // to distinguish from the colon in a ternary... which needs
636 // different spacing.
637 result.append(": ");
638 break;
639
640 case Token.COLON:
641 if (Token.EOL == getNext(source, length, i))
642 // it's the end of a label
643 result.append(':');
644 else
645 // it's the middle part of a ternary
646 result.append(" : ");
647 break;
648
649 case Token.OR:
650 result.append(" || ");
651 break;
652
653 case Token.AND:
654 result.append(" && ");
655 break;
656
657 case Token.BITOR:
658 result.append(" | ");
659 break;
660
661 case Token.BITXOR:
662 result.append(" ^ ");
663 break;
664
665 case Token.BITAND:
666 result.append(" & ");
667 break;
668
669 case Token.SHEQ:
670 result.append(" === ");
671 break;
672
673 case Token.SHNE:
674 result.append(" !== ");
675 break;
676
677 case Token.EQ:
678 result.append(" == ");
679 break;
680
681 case Token.NE:
682 result.append(" != ");
683 break;
684
685 case Token.LE:
686 result.append(" <= ");
687 break;
688
689 case Token.LT:
690 result.append(" < ");
691 break;
692
693 case Token.GE:
694 result.append(" >= ");
695 break;
696
697 case Token.GT:
698 result.append(" > ");
699 break;
700
701 case Token.INSTANCEOF:
702 result.append(" instanceof ");
703 break;
704
705 case Token.LSH:
706 result.append(" << ");
707 break;
708
709 case Token.RSH:
710 result.append(" >> ");
711 break;
712
713 case Token.URSH:
714 result.append(" >>> ");
715 break;
716
717 case Token.TYPEOF:
718 result.append("typeof ");
719 break;
720
721 case Token.VOID:
722 result.append("void ");
723 break;
724
725 case Token.CONST:
726 result.append("const ");
727 break;
728
729 case Token.YIELD:
730 result.append("yield ");
731 break;
732
733 case Token.NOT:
734 result.append('!');
735 break;
736
737 case Token.BITNOT:
738 result.append('~');
739 break;
740
741 case Token.POS:
742 result.append('+');
743 break;
744
745 case Token.NEG:
746 result.append('-');
747 break;
748
749 case Token.INC:
750 result.append("++");
751 break;
752
753 case Token.DEC:
754 result.append("--");
755 break;
756
757 case Token.ADD:
758 result.append(" + ");
759 break;
760
761 case Token.SUB:
762 result.append(" - ");
763 break;
764
765 case Token.MUL:
766 result.append(" * ");
767 break;
768
769 case Token.DIV:
770 result.append(" / ");
771 break;
772
773 case Token.MOD:
774 result.append(" % ");
775 break;
776
777 case Token.COLONCOLON:
778 result.append("::");
779 break;
780
781 case Token.DOTDOT:
782 result.append("..");
783 break;
784
785 case Token.DOTQUERY:
786 result.append(".(");
787 break;
788
789 case Token.XMLATTR:
790 result.append('@');
791 break;
792
793 case Token.DEBUGGER:
794 result.append("debugger;\n");
795 break;
796
797 case Token.ARROW:
798 result.append(" => ");
799 break;
800
801 default:
802 // If we don't know how to decompile it, raise an exception.
803 throw new RuntimeException("Token: " +
804 Token.name(source.charAt(i)));
805 }
806 ++i;
807 }
808
809 if (!toSource) {
810 // add that trailing newline if it's an outermost function.
811 if (!justFunctionBody)
812 result.append('\n');
813 } else {
814 if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) {
815 result.append(')');
816 }
817 }
818
819 return result.toString();
820 }
821
822 private static int getNext(String source, int length, int i)
823 {
824 return (i + 1 < length) ? source.charAt(i + 1) : Token.EOF;
825 }
826
827 private static int getSourceStringEnd(String source, int offset)
828 {
829 return printSourceString(source, offset, false, null);
830 }
831
832 private static int printSourceString(String source, int offset,
833 boolean asQuotedString,
834 StringBuilder sb)
835 {
836 int length = source.charAt(offset);
837 ++offset;
838 if ((0x8000 & length) != 0) {
839 length = ((0x7FFF & length) << 16) | source.charAt(offset);
840 ++offset;
841 }
842 if (sb != null) {
843 String str = source.substring(offset, offset + length);
844 if (!asQuotedString) {
845 sb.append(str);
846 } else {
847 sb.append('"');
848 sb.append(ScriptRuntime.escapeString(str));
849 sb.append('"');
850 }
851 }
852 return offset + length;
853 }
854
855 private static int printSourceNumber(String source, int offset,
856 StringBuilder sb)
857 {
858 double number = 0.0;
859 char type = source.charAt(offset);
860 ++offset;
861 if (type == 'S') {
862 if (sb != null) {
863 int ival = source.charAt(offset);
864 number = ival;
865 }
866 ++offset;
867 } else if (type == 'J' || type == 'D') {
868 if (sb != null) {
869 long lbits;
870 lbits = (long)source.charAt(offset) << 48;
871 lbits |= (long)source.charAt(offset + 1) << 32;
872 lbits |= (long)source.charAt(offset + 2) << 16;
873 lbits |= source.charAt(offset + 3);
874 if (type == 'J') {
875 number = lbits;
876 } else {
877 number = Double.longBitsToDouble(lbits);
878 }
879 }
880 offset += 4;
881 } else {
882 // Bad source
883 throw new RuntimeException();
884 }
885 if (sb != null) {
886 sb.append(ScriptRuntime.numberToString(number, 10));
887 }
888 return offset;
889 }
890
891 private char[] sourceBuffer = new char[128];
892
893 // Per script/function source buffer top: parent source does not include a
894 // nested functions source and uses function index as a reference instead.
895 private int sourceTop;
896
897 // whether to do a debug print of the source information, when decompiling.
898 private static final boolean printSource = false;
899
900 }