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();
179 this.globalScope.dump();
186 print (" ".substring(0, this.braceNesting*2) + str);
188 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
192 //println("<B>LOG:</B>" + str + "<BR/>");
199 parseScope : function(scope) // parse a token stream..
201 //this.timerPrint("parseScope EnterScope");
202 //this.log(">>> ENTER SCOPE" + this.scopes.length);
208 var expressionBraceNesting = this.braceNesting + 0;
210 var parensNesting = 0;
212 var isObjectLitAr = [ false ];
216 //var scopeIndent = '';
217 //this.scopes.forEach(function() {
218 // scopeIndent += ' ';
220 //print(">> ENTER SCOPE");
225 token = this.ts.lookTok(1);
227 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
228 //this.dumpToken(token , this.scopes, this.braceNesting);
229 //print('SCOPE:' + token.toString());
230 //this.log(token.data);
231 //if (token.type == 'NAME') {
232 // print('*' + token.data);
234 switch(token.type + '.' + token.name) {
236 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
237 //print('SCOPE-VAR:' + token.toString());
238 var vstart = this.ts.cursor +1;
240 //this.log("parseScope GOT VAR/CONST : " + token.toString());
242 token = this.ts.nextTok();
243 //!this.debug|| print( token.toString());
244 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
245 if (!token) { // can return false at EOF!
248 if (token.name == "VAR" || token.data == ',') { // kludge..
251 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
252 if (token.type != "NAME") {
253 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
254 print(this.ts.tokens[i].toString());
257 print( "var without ident");
262 if (this.mode == "BUILDING_SYMBOL_TREE") {
263 identifier = scope.getIdentifier(token.data,token) ;
265 if (identifier == false) {
266 scope.declareIdentifier(token.data, token);
268 token.identifier = identifier;
269 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
273 token = this.ts.nextTok();
274 !this.debug|| print(token.toString());
276 assert token.getType() == Token.SEMI ||
277 token.getType() == Token.ASSIGN ||
278 token.getType() == Token.COMMA ||
279 token.getType() == Token.IN;
281 if (token.name == "IN") {
284 //var bn = this.braceNesting;
285 var bn = this.braceNesting;
288 if (!token || token.type == 'VOID' || token.data == ',') {
292 token = this.ts.nextTok();
296 this.ts = new TokenStream(nts);
297 this.parseExpression(scope);
301 this.braceNesting = bn;
302 //this.braceNesting = bn;
303 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
305 token = this.ts.lookTok(1);
307 // print("AFTER EXP: " + token.toString());
308 if (token.data == ';') {
315 //this.ts.dump(vstart , this.ts.cursor);
320 case "KEYW.FUNCTION":
321 //if (this.mode == 'BUILDING_SYMBOL_TREE')
322 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
323 //println("<i>"+token.data+"</i>");
324 var bn = this.braceNesting;
325 this.parseFunctionDeclaration(scope);
326 this.braceNesting = bn;
329 case "PUNC.LEFT_CURLY": // {
330 case "PUNC.LEFT_PAREN": // (
331 case "PUNC.LEFT_BRACE": // [
332 //print('SCOPE-CURLY/PAREN:' + token.toString());
333 //println("<i>"+token.data+"</i>");
337 // { a : ... , c : .... }
339 for (var prop in token.props) {
342 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
343 if (token.props[prop].val[0].data == 'function') {
344 // parse a function..
345 this.ts = new TokenStream(token.props[prop].val);
347 this.parseFunctionDeclaration(scope);
353 this.ts = new TokenStream(token.props[prop].val);
354 this.parseExpression(scope);
359 // it's an object literal..
360 // the values could be replaced..
364 // ( ... ) or { .... } not object literals..
367 for (var xx =0; xx < token.items.length; xx++) {
368 expr = token.items[xx];
369 //token.items.forEach(function(expr) {
370 //print(expr.toString());
371 _this.ts = new TokenStream(expr);
372 //if (curTS.data == '(') {
373 _this.parseScope(scope)
375 // _this.parseExpression(scope)
380 //print("NOT PROPS"); Seed.quit();
382 //isObjectLitAr.push(false);
383 //this.braceNesting++;
385 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
388 case "PUNC.RIGHT_CURLY": // }
389 //print("<< EXIT SCOPE");
393 //print('SCOPE-WITH:' + token.toString());
394 //println("<i>"+token.data+"</i>");
395 if (this.mode == "BUILDING_SYMBOL_TREE") {
396 // Inside a 'with' block, it is impossible to figure out
397 // statically whether a symbol is a local variable or an
398 // object member. As a consequence, the only thing we can
399 // do is turn the obfuscation off for the highest scope
400 // containing the 'with' block.
401 this.protectScopeFromObfuscation(scope);
402 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
407 //print('SCOPE-CATCH:' + token.toString());
408 //println("<i>"+token.data+"</i>");
409 this.parseCatch(scope);
412 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
413 case "STRN.SINGLE_QUOTE":
414 // print('SCOPE-STRING:' + token.toString());
415 //println("<i>"+token.data+"</i>");
417 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
418 // then we are in an object lit.. -> we need to flag the brace as such...
420 isObjectLitAr.push(true);
421 //print(">>>>>> OBJLIT REPUSH(true)");
423 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
425 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
426 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
427 // see if we can replace..
428 // remove the quotes..
429 // should do a bit more checking!!!! (what about wierd char's in the string..
430 var str = token.data.substring(1,token.data.length-1);
431 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
442 //print('SCOPE-NAME:' + token.toString());
443 //print("DEAL WITH NAME:");
445 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
446 // skip anyting with "." before it..!!
448 if (this.ts.lookTok(-1).data == ".") {
449 // skip, it's an object prop.
450 //println("<i>"+token.data+"</i>");
453 //print("SYMBOL: " + token.toString());
456 if (symbol == 'this') {
459 if (this.mode == 'PASS2_SYMBOL_TREE') {
461 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
463 //print ("MUNGE?" + symbol);
465 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
467 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
468 identifier = this.getIdentifier(symbol, scope, token);
470 if (identifier == false) {
471 // BUG!find out where builtin is defined...
472 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
473 // Here, we found an undeclared and un-namespaced symbol that is
474 // 3 characters or less in length. Declare it in the global scope.
475 // We don't need to declare longer symbols since they won't cause
476 // any conflict with other munged symbols.
477 this.globalScope.declareIdentifier(symbol, token);
478 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
481 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
483 token.identifier = identifier;
484 identifier.refcount++;
489 //println("<B>SID</B>");
491 if (token.type != 'KEYW') {
494 //print('SCOPE-KEYW:' + token.toString());
495 // print("Check eval:");
499 if (this.mode == 'BUILDING_SYMBOL_TREE') {
501 if (token.name == "EVAL") {
503 //print(JSON.stringify(token, null,4));
504 // look back one and see if we can find a comment!!!
505 //if (this.ts.look(-1).type == "COMM") {
506 if (token.prefix && token.prefix.match(/eval/)) {
507 // look for eval:var:noreplace\n
510 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
511 //print("GOT: " + a);
512 var hi = _t.getIdentifier(a, scope, token);
513 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
515 // print("PROTECT "+a+" from munge");
516 //print(JSON.stringify(hi,null,4));
526 this.protectScopeFromObfuscation(scope);
527 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);
539 //print("parseScope TOK : " + token.toString());
540 token = this.ts.nextTok();
541 //if (this.ts.nextT()) break;
544 //print("<<< EXIT SCOPE");
545 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
549 parseExpression : function(scope) {
551 // Parse the expression until we encounter a comma or a semi-colon
552 // in the same brace nesting, bracket nesting and paren nesting.
553 // Parse functions if any...
554 //println("<i>EXP</i><BR/>");
555 !this.debug || print("PARSE EXPR");
558 // for printing stuff..
567 var expressionBraceNesting = this.braceNesting + 0;
568 var bracketNesting = 0;
569 var parensNesting = 0;
571 var isObjectLitAr = [ false ];
576 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
577 while ((token = this.ts.nextTok())) {
582 // moved out of loop?
583 currentScope = this.scopes[this.scopes.length-1];
585 var scopeIndent = '';
586 this.scopes.forEach(function() {
591 //this.dumpToken(token, this.scopes, this.braceNesting );
592 //print('EXPR' + token.toString());
595 //println("<i>"+token.data+"</i>");
596 //this.log("EXP:" + token.data);
597 switch (token.type) {
599 //print("EXPR-PUNC:" + token.toString());
604 //print("<< EXIT EXPRESSION");
612 case '(': //Token.LP:
613 case '{': //Token.LC:
614 case '[': //Token.LB:
615 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
616 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
617 //println("<i>"+token.data+"</i>");
621 for (var prop in token.props) {
622 if (!token.props[prop].val.length) {
623 print(JSON.stringify(token.props, null,4));
626 if (token.props[prop].val[0].data == 'function') {
627 // parse a function..
628 this.ts = new TokenStream(token.props[prop].val);
630 this.parseFunctionDeclaration(scope);
635 this.ts = new TokenStream(token.props[prop].val);
636 this.parseExpression(scope);
641 // it's an object literal..
642 // the values could be replaced..
648 token.items.forEach(function(expr) {
649 _this.ts = new TokenStream(expr);
650 _this.parseExpression(scope)
656 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
663 case ')': //Token.RP:
664 case ']': //Token.RB:
665 case '}': //Token.RB:
666 //print("<< EXIT EXPRESSION");
679 case 'STRN': // used for object lit detection..
680 //if (this.mode == 'BUILDING_SYMBOL_TREE')
681 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
689 if (this.mode == 'BUILDING_SYMBOL_TREE') {
691 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
693 //print("EXPR-NAME:" + token.toString());
696 //print("in NAME = " + token.toString());
697 //print("in NAME 0: " + this.ts.look(0).toString());
698 //print("in NAME 2: " + this.ts.lookTok(2).toString());
700 //print(this.ts.lookTok(-1).data);
702 if (this.ts.lookTok(-1).data == ".") {
706 if (symbol == 'this') {
710 if (this.mode == 'PASS2_SYMBOL_TREE') {
712 identifier = this.getIdentifier(symbol, scope, token);
713 //println("<B>??</B>");
714 if (identifier == false) {
716 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
717 // Here, we found an undeclared and un-namespaced symbol that is
718 // 3 characters or less in length. Declare it in the global scope.
719 // We don't need to declare longer symbols since they won't cause
720 // any conflict with other munged symbols.
721 this.globalScope.declareIdentifier(symbol, token);
722 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
723 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
726 //print("undeclared:" + token.toString())
731 //println("<B>++</B>");
732 token.identifier = identifier;
733 identifier.refcount++;
742 //println("<B>EID</B>");
744 //if (this.mode == 'BUILDING_SYMBOL_TREE')
745 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
747 //print('EXPR-KEYW:' + token.toString());
748 if (token.name == "FUNCTION") {
750 this.parseFunctionDeclaration(scope);
756 if (this.mode == 'BUILDING_SYMBOL_TREE') {
758 if (token.name == "EVAL") {
759 //print(JSON.stringify(token,null,4));
760 if (token.prefix && token.prefix.match(/eval:var:/g)) {
761 // look for eval:var:noreplace\n
762 // print("GOT MATCH?");
764 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
766 //print("PROTECT: " + a);
769 var hi = _t.getIdentifier(a, scope, token);
770 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
772 // println("PROTECT "+a+" from munge");
780 this.protectScopeFromObfuscation(scope);
781 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
789 //if (this.mode == 'BUILDING_SYMBOL_TREE')
790 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
795 //print("<< EXIT EXPRESSION");
800 parseCatch : function(scope) {
807 //token = getToken(-1);
808 //assert token.getType() == Token.CATCH;
809 token = this.ts.nextTok(1);
810 token = this.ts.nextTok(1);
813 //print(JSON.stringify(this.ts,null,4));
814 //assert token.getType() == Token.LP; (
815 //token = this.ts.nextTok();
816 //assert token.getType() == Token.NAME;
818 symbol = token.items[0][0].data;
821 if (this.mode == 'BUILDING_SYMBOL_TREE') {
822 // We must declare the exception identifier in the containing function
823 // scope to avoid errors related to the obfuscation process. No need to
824 // display a warning if the symbol was already declared here...
825 scope.declareIdentifier(symbol, token.items[0][0]);
827 //?? why inc the refcount?? - that should be set when building the tree???
828 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
829 identifier.refcount++;
832 //token = this.ts.nextTok();
833 //assert token.getType() == Token.RP; // )
836 parseFunctionDeclaration : function(scope)
838 //print("PARSE FUNCTION");
844 var b4braceNesting = this.braceNesting + 0;
846 //this.logR("<B>PARSING FUNCTION</B>");
849 token = this.ts.nextTok();
850 if (token.type == "NAME") {
851 if (this.mode == 'BUILDING_SYMBOL_TREE') {
852 // Get the name of the function and declare it in the current scope.
854 if (scope.getIdentifier(symbol,token) != false) {
855 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
857 scope.declareIdentifier(symbol,token);
859 token = this.ts.nextTok();
863 // return function() {....
864 while (token.data != "(") {
865 //print(token.toString());
866 token = this.ts.nextTok();
871 //assert token.getType() == Token.LP;
872 if (this.mode == 'BUILDING_SYMBOL_TREE') {
873 fnScope = new Scope(1, scope, token.n, '', token);
875 //println("STORING SCOPE" + this.ts.cursor);
877 this.indexedScopes[token.id] = fnScope;
880 //qln("FETCHING SCOPE" + this.ts.cursor);
881 fnScope = this.indexedScopes[token.id];
883 //if (this.mode == 'BUILDING_SYMBOL_TREE')
884 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
885 // Parse function arguments.
886 var args = token.items;
887 for (var argpos =0; argpos < args.length; argpos++) {
889 token = args[argpos][0];
890 //print ("FUNC ARGS: " + token.toString())
891 //assert token.getType() == Token.NAME ||
892 // token.getType() == Token.COMMA;
893 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
895 identifier = fnScope.declareIdentifier(symbol,token);
896 if (symbol == "$super" && argpos == 0) {
897 // Exception for Prototype 1.6...
898 identifier.preventMunging();
904 token = this.ts.nextTok();
905 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
907 //print(token.toString());
908 // assert token.getType() == Token.LC;
909 //this.braceNesting++;
911 //token = this.ts.nextTok();
912 //print(token.toString());
915 token.items.forEach(function(tar) {
916 _this.ts = new TokenStream(tar);
917 _this.parseScope(fnScope);
922 //print(JSON.stringify(this.ts,null,4));
923 //this.parseScope(fnScope);
925 // now pop it off the stack!!!
927 //this.braceNesting = b4braceNesting;
928 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
929 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
930 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
933 protectScopeFromObfuscation : function(scope) {
934 //assert scope != null;
936 if (scope == this.globalScope) {
937 // The global scope does not get obfuscated,
938 // so we don't need to worry about it...
942 // Find the highest local scope containing the specified scope.
943 while (scope && scope.parent != this.globalScope) {
944 scope = scope.parent;
947 //assert scope.getParentScope() == globalScope;
948 scope.preventMunging();
951 getIdentifier: function(symbol, scope, token) {
953 while (scope != false) {
954 identifier = scope.getIdentifier(symbol, token);
955 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
959 scope = scope.parent;