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 for (var xx =0; xx < token.items.length; xx++) {
366 expr = token.items[i];
367 //token.items.forEach(function(expr) {
368 //print(expr.toString());
369 _this.ts = new TokenStream(expr);
370 //if (curTS.data == '(') {
371 _this.parseScope(scope)
373 // _this.parseExpression(scope)
378 //print("NOT PROPS"); Seed.quit();
380 //isObjectLitAr.push(false);
381 //this.braceNesting++;
383 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
386 case "PUNC.RIGHT_CURLY": // }
387 //print("<< EXIT SCOPE");
391 //print('SCOPE-WITH:' + token.toString());
392 //println("<i>"+token.data+"</i>");
393 if (this.mode == "BUILDING_SYMBOL_TREE") {
394 // Inside a 'with' block, it is impossible to figure out
395 // statically whether a symbol is a local variable or an
396 // object member. As a consequence, the only thing we can
397 // do is turn the obfuscation off for the highest scope
398 // containing the 'with' block.
399 this.protectScopeFromObfuscation(scope);
400 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
405 //print('SCOPE-CATCH:' + token.toString());
406 //println("<i>"+token.data+"</i>");
407 this.parseCatch(scope);
410 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
411 case "STRN.SINGLE_QUOTE":
412 // print('SCOPE-STRING:' + token.toString());
413 //println("<i>"+token.data+"</i>");
415 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
416 // then we are in an object lit.. -> we need to flag the brace as such...
418 isObjectLitAr.push(true);
419 //print(">>>>>> OBJLIT REPUSH(true)");
421 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
423 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
424 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
425 // see if we can replace..
426 // remove the quotes..
427 // should do a bit more checking!!!! (what about wierd char's in the string..
428 var str = token.data.substring(1,token.data.length-1);
429 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
440 //print('SCOPE-NAME:' + token.toString());
441 //print("DEAL WITH NAME:");
443 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
444 // skip anyting with "." before it..!!
446 if (this.ts.lookTok(-1).data == ".") {
447 // skip, it's an object prop.
448 //println("<i>"+token.data+"</i>");
451 //print("SYMBOL: " + token.toString());
454 if (symbol == 'this') {
457 if (this.mode == 'PASS2_SYMBOL_TREE') {
459 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
461 //print ("MUNGE?" + symbol);
463 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
465 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
466 identifier = this.getIdentifier(symbol, scope, token);
468 if (identifier == false) {
469 // BUG!find out where builtin is defined...
470 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
471 // Here, we found an undeclared and un-namespaced symbol that is
472 // 3 characters or less in length. Declare it in the global scope.
473 // We don't need to declare longer symbols since they won't cause
474 // any conflict with other munged symbols.
475 this.globalScope.declareIdentifier(symbol, token);
476 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
479 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
481 token.identifier = identifier;
482 identifier.refcount++;
487 //println("<B>SID</B>");
489 if (token.type != 'KEYW') {
492 //print('SCOPE-KEYW:' + token.toString());
493 // print("Check eval:");
497 if (this.mode == 'BUILDING_SYMBOL_TREE') {
499 if (token.name == "EVAL") {
501 //print(JSON.stringify(token, null,4));
502 // look back one and see if we can find a comment!!!
503 //if (this.ts.look(-1).type == "COMM") {
504 if (token.prefix && token.prefix.match(/eval/)) {
505 // look for eval:var:noreplace\n
508 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
509 //print("GOT: " + a);
510 var hi = _t.getIdentifier(a, scope, token);
511 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
513 // print("PROTECT "+a+" from munge");
514 //print(JSON.stringify(hi,null,4));
524 this.protectScopeFromObfuscation(scope);
525 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);
537 //print("parseScope TOK : " + token.toString());
538 token = this.ts.nextTok();
539 //if (this.ts.nextT()) break;
542 //print("<<< EXIT SCOPE");
543 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
547 parseExpression : function(scope) {
549 // Parse the expression until we encounter a comma or a semi-colon
550 // in the same brace nesting, bracket nesting and paren nesting.
551 // Parse functions if any...
552 //println("<i>EXP</i><BR/>");
553 !this.debug || print("PARSE EXPR");
556 // for printing stuff..
565 var expressionBraceNesting = this.braceNesting + 0;
566 var bracketNesting = 0;
567 var parensNesting = 0;
569 var isObjectLitAr = [ false ];
574 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
575 while ((token = this.ts.nextTok())) {
580 // moved out of loop?
581 currentScope = this.scopes[this.scopes.length-1];
583 var scopeIndent = '';
584 this.scopes.forEach(function() {
589 //this.dumpToken(token, this.scopes, this.braceNesting );
590 //print('EXPR' + token.toString());
593 //println("<i>"+token.data+"</i>");
594 //this.log("EXP:" + token.data);
595 switch (token.type) {
597 //print("EXPR-PUNC:" + token.toString());
602 //print("<< EXIT EXPRESSION");
610 case '(': //Token.LP:
611 case '{': //Token.LC:
612 case '[': //Token.LB:
613 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
614 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
615 //println("<i>"+token.data+"</i>");
619 for (var prop in token.props) {
620 if (!token.props[prop].val.length) {
621 print(JSON.stringify(token.props, null,4));
624 if (token.props[prop].val[0].data == 'function') {
625 // parse a function..
626 this.ts = new TokenStream(token.props[prop].val);
628 this.parseFunctionDeclaration(scope);
633 this.ts = new TokenStream(token.props[prop].val);
634 this.parseExpression(scope);
639 // it's an object literal..
640 // the values could be replaced..
646 token.items.forEach(function(expr) {
647 _this.ts = new TokenStream(expr);
648 _this.parseExpression(scope)
654 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
661 case ')': //Token.RP:
662 case ']': //Token.RB:
663 case '}': //Token.RB:
664 //print("<< EXIT EXPRESSION");
677 case 'STRN': // used for object lit detection..
678 //if (this.mode == 'BUILDING_SYMBOL_TREE')
679 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
687 if (this.mode == 'BUILDING_SYMBOL_TREE') {
689 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
691 //print("EXPR-NAME:" + token.toString());
694 //print("in NAME = " + token.toString());
695 //print("in NAME 0: " + this.ts.look(0).toString());
696 //print("in NAME 2: " + this.ts.lookTok(2).toString());
698 //print(this.ts.lookTok(-1).data);
700 if (this.ts.lookTok(-1).data == ".") {
704 if (symbol == 'this') {
708 if (this.mode == 'PASS2_SYMBOL_TREE') {
710 identifier = this.getIdentifier(symbol, scope, token);
711 //println("<B>??</B>");
712 if (identifier == false) {
714 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
715 // Here, we found an undeclared and un-namespaced symbol that is
716 // 3 characters or less in length. Declare it in the global scope.
717 // We don't need to declare longer symbols since they won't cause
718 // any conflict with other munged symbols.
719 this.globalScope.declareIdentifier(symbol, token);
720 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
721 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
724 //print("undeclared:" + token.toString())
729 //println("<B>++</B>");
730 token.identifier = identifier;
731 identifier.refcount++;
740 //println("<B>EID</B>");
742 //if (this.mode == 'BUILDING_SYMBOL_TREE')
743 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
745 //print('EXPR-KEYW:' + token.toString());
746 if (token.name == "FUNCTION") {
748 this.parseFunctionDeclaration(scope);
754 if (this.mode == 'BUILDING_SYMBOL_TREE') {
756 if (token.name == "EVAL") {
757 //print(JSON.stringify(token,null,4));
758 if (token.prefix && token.prefix.match(/eval:var:/g)) {
759 // look for eval:var:noreplace\n
760 // print("GOT MATCH?");
762 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
764 //print("PROTECT: " + a);
767 var hi = _t.getIdentifier(a, scope, token);
768 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
770 // println("PROTECT "+a+" from munge");
778 this.protectScopeFromObfuscation(scope);
779 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
787 //if (this.mode == 'BUILDING_SYMBOL_TREE')
788 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
793 //print("<< EXIT EXPRESSION");
798 parseCatch : function(scope) {
805 //token = getToken(-1);
806 //assert token.getType() == Token.CATCH;
807 token = this.ts.nextTok(1);
808 token = this.ts.nextTok(1);
811 //print(JSON.stringify(this.ts,null,4));
812 //assert token.getType() == Token.LP; (
813 //token = this.ts.nextTok();
814 //assert token.getType() == Token.NAME;
816 symbol = token.items[0][0].data;
819 if (this.mode == 'BUILDING_SYMBOL_TREE') {
820 // We must declare the exception identifier in the containing function
821 // scope to avoid errors related to the obfuscation process. No need to
822 // display a warning if the symbol was already declared here...
823 scope.declareIdentifier(symbol, token.items[0][0]);
825 //?? why inc the refcount?? - that should be set when building the tree???
826 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
827 identifier.refcount++;
830 //token = this.ts.nextTok();
831 //assert token.getType() == Token.RP; // )
834 parseFunctionDeclaration : function(scope)
836 //print("PARSE FUNCTION");
842 var b4braceNesting = this.braceNesting + 0;
844 //this.logR("<B>PARSING FUNCTION</B>");
847 token = this.ts.nextTok();
848 if (token.type == "NAME") {
849 if (this.mode == 'BUILDING_SYMBOL_TREE') {
850 // Get the name of the function and declare it in the current scope.
852 if (scope.getIdentifier(symbol,token) != false) {
853 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
855 scope.declareIdentifier(symbol,token);
857 token = this.ts.nextTok();
861 // return function() {....
862 while (token.data != "(") {
863 //print(token.toString());
864 token = this.ts.nextTok();
869 //assert token.getType() == Token.LP;
870 if (this.mode == 'BUILDING_SYMBOL_TREE') {
871 fnScope = new Scope(1, scope, token.n, '', token);
873 //println("STORING SCOPE" + this.ts.cursor);
875 this.indexedScopes[token.id] = fnScope;
878 //qln("FETCHING SCOPE" + this.ts.cursor);
879 fnScope = this.indexedScopes[token.id];
881 //if (this.mode == 'BUILDING_SYMBOL_TREE')
882 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
883 // Parse function arguments.
884 var args = token.items;
885 for (var argpos =0; argpos < args.length; argpos++) {
887 token = args[argpos][0];
888 //print ("FUNC ARGS: " + token.toString())
889 //assert token.getType() == Token.NAME ||
890 // token.getType() == Token.COMMA;
891 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
893 identifier = fnScope.declareIdentifier(symbol,token);
894 if (symbol == "$super" && argpos == 0) {
895 // Exception for Prototype 1.6...
896 identifier.preventMunging();
902 token = this.ts.nextTok();
903 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
905 //print(token.toString());
906 // assert token.getType() == Token.LC;
907 //this.braceNesting++;
909 //token = this.ts.nextTok();
910 //print(token.toString());
913 token.items.forEach(function(tar) {
914 _this.ts = new TokenStream(tar);
915 _this.parseScope(fnScope);
920 //print(JSON.stringify(this.ts,null,4));
921 //this.parseScope(fnScope);
923 // now pop it off the stack!!!
925 //this.braceNesting = b4braceNesting;
926 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
927 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
928 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
931 protectScopeFromObfuscation : function(scope) {
932 //assert scope != null;
934 if (scope == this.globalScope) {
935 // The global scope does not get obfuscated,
936 // so we don't need to worry about it...
940 // Find the highest local scope containing the specified scope.
941 while (scope && scope.parent != this.globalScope) {
942 scope = scope.parent;
945 //assert scope.getParentScope() == globalScope;
946 scope.preventMunging();
949 getIdentifier: function(symbol, scope, token) {
951 while (scope != false) {
952 identifier = scope.getIdentifier(symbol, token);
953 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
957 scope = scope.parent;