1 //<Script type="text/javascript">
3 const Scope = imports.Scope.Scope;
4 const TokenStream = imports.TokenStream.TokenStream;
8 * This code now uses the collapsed tree
14 const ScopeParser = function(ts) {
15 this.ts = ts; // {TokenStream}
18 this.timer = new Date() * 1;
22 // list of keywords that should not be used in object literals.
23 ScopeParser.idents = [
89 ScopeParser.prototype = {
91 timerPrint: function (str) {
92 var ntime = new Date() * 1;
93 var tdif = ntime -this.timer;
96 if (tdif > 100) { //slower ones..
99 println(pref+'['+tdif+']'+str);
103 //print('****************' + s);
104 this.warnings.push(s);
105 //println("WARNING:" + htmlescape(s) + "<BR>");
107 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
111 mode : "", //"BUILDING_SYMBOL_TREE",
113 indexedScopes : false,
120 buildSymbolTree : function()
125 this.braceNesting = 0;
127 // print(JSON.stringify(this.ts.tokens, null,4));
130 this.globalScope = new Scope(-1, false, -1, '');
131 this.indexedScopes = { 0 : this.globalScope };
133 this.mode = 'BUILDING_SYMBOL_TREE';
134 this.parseScope(this.globalScope);
136 //print("---------------END PASS 1 ---------------- ");
139 mungeSymboltree : function()
146 // One problem with obfuscation resides in the use of undeclared
147 // and un-namespaced global symbols that are 3 characters or less
148 // in length. Here is an example:
150 // var declaredGlobalVar;
152 // function declaredGlobalFn() {
154 // localvar = abc; // abc is an undeclared global symbol
157 // In the example above, there is a slim chance that localvar may be
158 // munged to 'abc', conflicting with the undeclared global symbol
159 // abc, creating a potential bug. The following code detects such
160 // global symbols. This must be done AFTER the entire file has been
161 // parsed, and BEFORE munging the symbol tree. Note that declaring
162 // extra symbols in the global scope won't hurt.
164 // Note: Since we go through all the tokens to do this, we also use
165 // the opportunity to count how many times each identifier is used.
168 this.braceNesting = 0;
169 this.mode = 'PASS2_SYMBOL_TREE';
171 //println("MUNGING?");
173 this.parseScope(this.globalScope);
175 //this.globalScope.dump();
178 this.globalScope.munge();
184 print (" ".substring(0, this.braceNesting*2) + str);
186 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
190 //println("<B>LOG:</B>" + str + "<BR/>");
197 parseScope : function(scope) // parse a token stream..
199 //this.timerPrint("parseScope EnterScope");
200 //this.log(">>> ENTER SCOPE" + this.scopes.length);
206 var expressionBraceNesting = this.braceNesting + 0;
208 var parensNesting = 0;
210 var isObjectLitAr = [ false ];
214 //var scopeIndent = '';
215 //this.scopes.forEach(function() {
216 // scopeIndent += ' ';
218 //print(">> ENTER SCOPE");
223 token = this.ts.lookTok(1);
225 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
226 //this.dumpToken(token , this.scopes, this.braceNesting);
227 //print('SCOPE:' + token.toString());
228 //this.log(token.data);
229 //if (token.type == 'NAME') {
230 // print('*' + token.data);
232 switch(token.type + '.' + token.name) {
234 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
235 //print('SCOPE-VAR:' + token.toString());
236 var vstart = this.ts.cursor +1;
238 //this.log("parseScope GOT VAR/CONST : " + token.toString());
240 token = this.ts.nextTok();
241 //!this.debug|| print( token.toString());
242 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
243 if (!token) { // can return false at EOF!
246 if (token.name == "VAR" || token.data == ',') { // kludge..
249 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
250 if (token.type != "NAME") {
251 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
252 print(this.ts.tokens[i].toString());
255 print( "var without ident");
260 if (this.mode == "BUILDING_SYMBOL_TREE") {
261 identifier = scope.getIdentifier(token.data,token) ;
263 if (identifier == false) {
264 scope.declareIdentifier(token.data, token);
266 token.identifier = identifier;
267 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
271 token = this.ts.nextTok();
272 !this.debug|| print(token.toString());
274 assert token.getType() == Token.SEMI ||
275 token.getType() == Token.ASSIGN ||
276 token.getType() == Token.COMMA ||
277 token.getType() == Token.IN;
279 if (token.name == "IN") {
282 //var bn = this.braceNesting;
283 var bn = this.braceNesting;
286 if (!token || token.type == 'VOID' || token.data == ',') {
290 token = this.ts.nextTok();
294 this.ts = new TokenStream(nts);
295 this.parseExpression(scope);
299 this.braceNesting = bn;
300 //this.braceNesting = bn;
301 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
303 token = this.ts.lookTok(1);
305 // print("AFTER EXP: " + token.toString());
306 if (token.data == ';') {
313 //this.ts.dump(vstart , this.ts.cursor);
318 case "KEYW.FUNCTION":
319 //if (this.mode == 'BUILDING_SYMBOL_TREE')
320 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
321 //println("<i>"+token.data+"</i>");
322 var bn = this.braceNesting;
323 this.parseFunctionDeclaration(scope);
324 this.braceNesting = bn;
327 case "PUNC.LEFT_CURLY": // {
328 case "PUNC.LEFT_PAREN": // (
329 case "PUNC.LEFT_BRACE": // [
330 //print('SCOPE-CURLY/PAREN:' + token.toString());
331 //println("<i>"+token.data+"</i>");
335 // { a : ... , c : .... }
337 for (var prop in token.props) {
340 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
341 if (token.props[prop].val[0].data == 'function') {
342 // parse a function..
343 this.ts = new TokenStream(token.props[prop].val);
345 this.parseFunctionDeclaration(scope);
351 this.ts = new TokenStream(token.props[prop].val);
352 this.parseExpression(scope);
357 // it's an object literal..
358 // the values could be replaced..
362 // ( ... ) or { .... } not object literals..
365 token.items.forEach(function(expr) {
366 //print(expr.toString());
367 _this.ts = new TokenStream(expr);
368 //if (curTS.data == '(') {
369 _this.parseScope(scope)
371 // _this.parseExpression(scope)
376 //print("NOT PROPS"); Seed.quit();
378 //isObjectLitAr.push(false);
379 //this.braceNesting++;
381 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
384 case "PUNC.RIGHT_CURLY": // }
385 //print("<< EXIT SCOPE");
389 //print('SCOPE-WITH:' + token.toString());
390 //println("<i>"+token.data+"</i>");
391 if (this.mode == "BUILDING_SYMBOL_TREE") {
392 // Inside a 'with' block, it is impossible to figure out
393 // statically whether a symbol is a local variable or an
394 // object member. As a consequence, the only thing we can
395 // do is turn the obfuscation off for the highest scope
396 // containing the 'with' block.
397 this.protectScopeFromObfuscation(scope);
398 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
403 //print('SCOPE-CATCH:' + token.toString());
404 //println("<i>"+token.data+"</i>");
405 this.parseCatch(scope);
408 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
409 case "STRN.SINGLE_QUOTE":
410 // print('SCOPE-STRING:' + token.toString());
411 //println("<i>"+token.data+"</i>");
413 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
414 // then we are in an object lit.. -> we need to flag the brace as such...
416 isObjectLitAr.push(true);
417 //print(">>>>>> OBJLIT REPUSH(true)");
419 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
421 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
422 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
423 // see if we can replace..
424 // remove the quotes..
425 // should do a bit more checking!!!! (what about wierd char's in the string..
426 var str = token.data.substring(1,token.data.length-1);
427 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
438 //print('SCOPE-NAME:' + token.toString());
439 //print("DEAL WITH NAME:");
441 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
442 // skip anyting with "." before it..!!
444 if (this.ts.lookTok(-1).data == ".") {
445 // skip, it's an object prop.
446 //println("<i>"+token.data+"</i>");
449 //print("SYMBOL: " + token.toString());
452 if (symbol == 'this') {
455 if (this.mode == 'PASS2_SYMBOL_TREE') {
457 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
459 //print ("MUNGE?" + symbol);
461 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
463 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
464 identifier = this.getIdentifier(symbol, scope, token);
466 if (identifier == false) {
467 // BUG!find out where builtin is defined...
468 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
469 // Here, we found an undeclared and un-namespaced symbol that is
470 // 3 characters or less in length. Declare it in the global scope.
471 // We don't need to declare longer symbols since they won't cause
472 // any conflict with other munged symbols.
473 this.globalScope.declareIdentifier(symbol, token);
474 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
477 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
479 token.identifier = identifier;
480 identifier.refcount++;
485 //println("<B>SID</B>");
487 if (token.type != 'KEYW') {
490 //print('SCOPE-KEYW:' + token.toString());
491 // print("Check eval:");
495 if (this.mode == 'BUILDING_SYMBOL_TREE') {
497 if (token.name == "EVAL") {
499 //print(JSON.stringify(token, null,4));
500 // look back one and see if we can find a comment!!!
501 //if (this.ts.look(-1).type == "COMM") {
502 if (token.prefix && token.prefix.match(/eval/)) {
503 // look for eval:var:noreplace\n
506 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
507 //print("GOT: " + a);
508 var hi = _t.getIdentifier(a, scope, token);
509 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
511 // print("PROTECT "+a+" from munge");
512 //print(JSON.stringify(hi,null,4));
522 this.protectScopeFromObfuscation(scope);
523 this.warn("Using 'eval' is not recommended. (use eval:var:noreplace in comments to optimize) " + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
535 //print("parseScope TOK : " + token.toString());
536 token = this.ts.nextTok();
537 //if (this.ts.nextT()) break;
540 //print("<<< EXIT SCOPE");
541 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
545 parseExpression : function(scope) {
547 // Parse the expression until we encounter a comma or a semi-colon
548 // in the same brace nesting, bracket nesting and paren nesting.
549 // Parse functions if any...
550 //println("<i>EXP</i><BR/>");
551 !this.debug || print("PARSE EXPR");
554 // for printing stuff..
563 var expressionBraceNesting = this.braceNesting + 0;
564 var bracketNesting = 0;
565 var parensNesting = 0;
567 var isObjectLitAr = [ false ];
572 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
573 while ((token = this.ts.nextTok())) {
578 // moved out of loop?
579 currentScope = this.scopes[this.scopes.length-1];
581 var scopeIndent = '';
582 this.scopes.forEach(function() {
587 //this.dumpToken(token, this.scopes, this.braceNesting );
588 //print('EXPR' + token.toString());
591 //println("<i>"+token.data+"</i>");
592 //this.log("EXP:" + token.data);
593 switch (token.type) {
595 //print("EXPR-PUNC:" + token.toString());
600 //print("<< EXIT EXPRESSION");
608 case '(': //Token.LP:
609 case '{': //Token.LC:
610 case '[': //Token.LB:
611 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
612 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
613 //println("<i>"+token.data+"</i>");
617 for (var prop in token.props) {
618 if (!token.props[prop].val.length) {
619 print(JSON.stringify(token.props, null,4));
622 if (token.props[prop].val[0].data == 'function') {
623 // parse a function..
624 this.ts = new TokenStream(token.props[prop].val);
626 this.parseFunctionDeclaration(scope);
631 this.ts = new TokenStream(token.props[prop].val);
632 this.parseExpression(scope);
637 // it's an object literal..
638 // the values could be replaced..
644 token.items.forEach(function(expr) {
645 _this.ts = new TokenStream(expr);
646 _this.parseExpression(scope)
652 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
659 case ')': //Token.RP:
660 case ']': //Token.RB:
661 case '}': //Token.RB:
662 //print("<< EXIT EXPRESSION");
675 case 'STRN': // used for object lit detection..
676 //if (this.mode == 'BUILDING_SYMBOL_TREE')
677 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
685 if (this.mode == 'BUILDING_SYMBOL_TREE') {
687 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
689 //print("EXPR-NAME:" + token.toString());
692 //print("in NAME = " + token.toString());
693 //print("in NAME 0: " + this.ts.look(0).toString());
694 //print("in NAME 2: " + this.ts.lookTok(2).toString());
696 //print(this.ts.lookTok(-1).data);
698 if (this.ts.lookTok(-1).data == ".") {
702 if (symbol == 'this') {
706 if (this.mode == 'PASS2_SYMBOL_TREE') {
708 identifier = this.getIdentifier(symbol, scope, token);
709 //println("<B>??</B>");
710 if (identifier == false) {
712 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
713 // Here, we found an undeclared and un-namespaced symbol that is
714 // 3 characters or less in length. Declare it in the global scope.
715 // We don't need to declare longer symbols since they won't cause
716 // any conflict with other munged symbols.
717 this.globalScope.declareIdentifier(symbol, token);
718 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
719 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
722 //print("undeclared:" + token.toString())
727 //println("<B>++</B>");
728 token.identifier = identifier;
729 identifier.refcount++;
738 //println("<B>EID</B>");
740 //if (this.mode == 'BUILDING_SYMBOL_TREE')
741 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
743 //print('EXPR-KEYW:' + token.toString());
744 if (token.name == "FUNCTION") {
746 this.parseFunctionDeclaration(scope);
752 if (this.mode == 'BUILDING_SYMBOL_TREE') {
754 if (token.name == "EVAL") {
755 //print(JSON.stringify(token,null,4));
756 if (token.prefix && token.prefix.match(/eval:var:/g)) {
757 // look for eval:var:noreplace\n
758 // print("GOT MATCH?");
760 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
762 //print("PROTECT: " + a);
765 var hi = _t.getIdentifier(a, scope, token);
766 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
768 // println("PROTECT "+a+" from munge");
776 this.protectScopeFromObfuscation(scope);
777 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
785 //if (this.mode == 'BUILDING_SYMBOL_TREE')
786 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
791 //print("<< EXIT EXPRESSION");
796 parseCatch : function(scope) {
803 //token = getToken(-1);
804 //assert token.getType() == Token.CATCH;
805 token = this.ts.nextTok(1);
806 token = this.ts.nextTok(1);
809 //print(JSON.stringify(this.ts,null,4));
810 //assert token.getType() == Token.LP; (
811 //token = this.ts.nextTok();
812 //assert token.getType() == Token.NAME;
814 symbol = token.items[0][0].data;
817 if (this.mode == 'BUILDING_SYMBOL_TREE') {
818 // We must declare the exception identifier in the containing function
819 // scope to avoid errors related to the obfuscation process. No need to
820 // display a warning if the symbol was already declared here...
821 scope.declareIdentifier(symbol, token.items[0][0]);
823 //?? why inc the refcount?? - that should be set when building the tree???
824 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
825 identifier.refcount++;
828 //token = this.ts.nextTok();
829 //assert token.getType() == Token.RP; // )
832 parseFunctionDeclaration : function(scope)
834 //print("PARSE FUNCTION");
840 var b4braceNesting = this.braceNesting + 0;
842 //this.logR("<B>PARSING FUNCTION</B>");
845 token = this.ts.nextTok();
846 if (token.type == "NAME") {
847 if (this.mode == 'BUILDING_SYMBOL_TREE') {
848 // Get the name of the function and declare it in the current scope.
850 if (scope.getIdentifier(symbol,token) != false) {
851 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
853 scope.declareIdentifier(symbol,token);
855 token = this.ts.nextTok();
859 // return function() {....
860 while (token.data != "(") {
861 //print(token.toString());
862 token = this.ts.nextTok();
867 //assert token.getType() == Token.LP;
868 if (this.mode == 'BUILDING_SYMBOL_TREE') {
869 fnScope = new Scope(1, scope, token.n, '', token);
871 //println("STORING SCOPE" + this.ts.cursor);
873 this.indexedScopes[token.id] = fnScope;
876 //qln("FETCHING SCOPE" + this.ts.cursor);
877 fnScope = this.indexedScopes[token.id];
879 //if (this.mode == 'BUILDING_SYMBOL_TREE')
880 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
881 // Parse function arguments.
882 var args = token.items;
883 for (var argpos =0; argpos < args.length; argpos++) {
885 token = args[argpos][0];
886 //print ("FUNC ARGS: " + token.toString())
887 //assert token.getType() == Token.NAME ||
888 // token.getType() == Token.COMMA;
889 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
891 identifier = fnScope.declareIdentifier(symbol,token);
892 if (symbol == "$super" && argpos == 0) {
893 // Exception for Prototype 1.6...
894 identifier.preventMunging();
900 token = this.ts.nextTok();
901 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
903 //print(token.toString());
904 // assert token.getType() == Token.LC;
905 //this.braceNesting++;
907 //token = this.ts.nextTok();
908 //print(token.toString());
911 token.items.forEach(function(tar) {
912 _this.ts = new TokenStream(tar);
913 _this.parseScope(fnScope);
918 //print(JSON.stringify(this.ts,null,4));
919 //this.parseScope(fnScope);
921 // now pop it off the stack!!!
923 //this.braceNesting = b4braceNesting;
924 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
925 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
926 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
929 protectScopeFromObfuscation : function(scope) {
930 //assert scope != null;
932 if (scope == this.globalScope) {
933 // The global scope does not get obfuscated,
934 // so we don't need to worry about it...
938 // Find the highest local scope containing the specified scope.
939 while (scope && scope.parent != this.globalScope) {
940 scope = scope.parent;
943 //assert scope.getParentScope() == globalScope;
944 scope.preventMunging();
947 getIdentifier: function(symbol, scope, token) {
949 while (scope != false) {
950 identifier = scope.getIdentifier(symbol, token);
951 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
955 scope = scope.parent;