6 public class ScopeParser : Object {
9 Gee.ArrayList<string> warnings;
16 //mode : "", //"BUILDING_SYMBOL_TREE",
18 Gee.HashMap<int,Scope> indexedScopes;
23 public ScopeParser(TokenStream ts) {
24 this.ts = ts; // {TokenStream}
25 this.warnings = new Gee.ArrayList<string>();
26 this.globalScope = new Scope(-1, false, -1, '');
27 this.indexedScopes = new Gee.HashMap<int,Scope>();
30 //this.timer = new Date() * 1;
103 //print('****************' + s);
104 this.warnings.add(s);
105 //println("WARNING:" + htmlescape(s) + "<BR>");
109 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
116 void buildSymbolTree()
121 this.braceNesting = 0;
123 // print(JSON.stringify(this.ts.tokens, null,4));
126 this.globalScope = new Scope(-1, false, -1, '');
127 this.indexedScopes = { 0 : this.globalScope };
129 this.mode = 'BUILDING_SYMBOL_TREE';
130 this.parseScope(this.globalScope);
132 //print("---------------END PASS 1 ---------------- ");
135 mungeSymboltree : function()
142 // One problem with obfuscation resides in the use of undeclared
143 // and un-namespaced global symbols that are 3 characters or less
144 // in length. Here is an example:
146 // var declaredGlobalVar;
148 // function declaredGlobalFn() {
150 // localvar = abc; // abc is an undeclared global symbol
153 // In the example above, there is a slim chance that localvar may be
154 // munged to 'abc', conflicting with the undeclared global symbol
155 // abc, creating a potential bug. The following code detects such
156 // global symbols. This must be done AFTER the entire file has been
157 // parsed, and BEFORE munging the symbol tree. Note that declaring
158 // extra symbols in the global scope won't hurt.
160 // Note: Since we go through all the tokens to do this, we also use
161 // the opportunity to count how many times each identifier is used.
164 this.braceNesting = 0;
165 this.mode = 'PASS2_SYMBOL_TREE';
167 //println("MUNGING?");
169 this.parseScope(this.globalScope);
171 //this.globalScope.dump();
174 this.globalScope.munge();
180 print (" ".substring(0, this.braceNesting*2) + str);
182 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
186 //println("<B>LOG:</B>" + str + "<BR/>");
193 parseScope : function(scope) // parse a token stream..
195 //this.timerPrint("parseScope EnterScope");
196 //this.log(">>> ENTER SCOPE" + this.scopes.length);
202 var expressionBraceNesting = this.braceNesting + 0;
204 var parensNesting = 0;
206 var isObjectLitAr = [ false ];
210 //var scopeIndent = '';
211 //this.scopes.forEach(function() {
212 // scopeIndent += ' ';
214 //print(">> ENTER SCOPE");
219 token = this.ts.lookTok(1);
221 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
222 //this.dumpToken(token , this.scopes, this.braceNesting);
223 //print('SCOPE:' + token.toString());
224 //this.log(token.data);
225 //if (token.type == 'NAME') {
226 // print('*' + token.data);
228 switch(token.type + '.' + token.name) {
230 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
231 //print('SCOPE-VAR:' + token.toString());
232 var vstart = this.ts.cursor +1;
234 //this.log("parseScope GOT VAR/CONST : " + token.toString());
236 token = this.ts.nextTok();
237 //!this.debug|| print( token.toString());
238 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
239 if (!token) { // can return false at EOF!
242 if (token.name == "VAR" || token.data == ',') { // kludge..
245 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
246 if (token.type != "NAME") {
247 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
248 print(this.ts.tokens[i].toString());
251 print( "var without ident");
256 if (this.mode == "BUILDING_SYMBOL_TREE") {
257 identifier = scope.getIdentifier(token.data,token) ;
259 if (identifier == false) {
260 scope.declareIdentifier(token.data, token);
262 token.identifier = identifier;
263 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
267 token = this.ts.nextTok();
268 !this.debug|| print(token.toString());
270 assert token.getType() == Token.SEMI ||
271 token.getType() == Token.ASSIGN ||
272 token.getType() == Token.COMMA ||
273 token.getType() == Token.IN;
275 if (token.name == "IN") {
278 //var bn = this.braceNesting;
279 var bn = this.braceNesting;
282 if (!token || token.type == 'VOID' || token.data == ',') {
286 token = this.ts.nextTok();
290 this.ts = new TokenStream(nts);
291 this.parseExpression(scope);
295 this.braceNesting = bn;
296 //this.braceNesting = bn;
297 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
299 token = this.ts.lookTok(1);
301 // print("AFTER EXP: " + token.toString());
302 if (token.data == ';') {
309 //this.ts.dump(vstart , this.ts.cursor);
314 case "KEYW.FUNCTION":
315 //if (this.mode == 'BUILDING_SYMBOL_TREE')
316 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
317 //println("<i>"+token.data+"</i>");
318 var bn = this.braceNesting;
319 this.parseFunctionDeclaration(scope);
320 this.braceNesting = bn;
323 case "PUNC.LEFT_CURLY": // {
324 case "PUNC.LEFT_PAREN": // (
325 case "PUNC.LEFT_BRACE": // [
326 //print('SCOPE-CURLY/PAREN:' + token.toString());
327 //println("<i>"+token.data+"</i>");
331 // { a : ... , c : .... }
333 for (var prop in token.props) {
336 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
337 if (token.props[prop].val[0].data == 'function') {
338 // parse a function..
339 this.ts = new TokenStream(token.props[prop].val);
341 this.parseFunctionDeclaration(scope);
347 this.ts = new TokenStream(token.props[prop].val);
348 this.parseExpression(scope);
353 // it's an object literal..
354 // the values could be replaced..
358 // ( ... ) or { .... } not object literals..
361 for (var xx =0; xx < token.items.length; xx++) {
362 expr = token.items[xx];
363 //token.items.forEach(function(expr) {
364 //print(expr.toString());
365 _this.ts = new TokenStream(expr);
366 //if (curTS.data == '(') {
367 _this.parseScope(scope)
369 // _this.parseExpression(scope)
374 //print("NOT PROPS"); Seed.quit();
376 //isObjectLitAr.push(false);
377 //this.braceNesting++;
379 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
382 case "PUNC.RIGHT_CURLY": // }
383 //print("<< EXIT SCOPE");
387 //print('SCOPE-WITH:' + token.toString());
388 //println("<i>"+token.data+"</i>");
389 if (this.mode == "BUILDING_SYMBOL_TREE") {
390 // Inside a 'with' block, it is impossible to figure out
391 // statically whether a symbol is a local variable or an
392 // object member. As a consequence, the only thing we can
393 // do is turn the obfuscation off for the highest scope
394 // containing the 'with' block.
395 this.protectScopeFromObfuscation(scope);
396 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
401 //print('SCOPE-CATCH:' + token.toString());
402 //println("<i>"+token.data+"</i>");
403 this.parseCatch(scope);
406 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
407 case "STRN.SINGLE_QUOTE":
408 // print('SCOPE-STRING:' + token.toString());
409 //println("<i>"+token.data+"</i>");
411 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
412 // then we are in an object lit.. -> we need to flag the brace as such...
414 isObjectLitAr.push(true);
415 //print(">>>>>> OBJLIT REPUSH(true)");
417 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
419 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
420 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
421 // see if we can replace..
422 // remove the quotes..
423 // should do a bit more checking!!!! (what about wierd char's in the string..
424 var str = token.data.substring(1,token.data.length-1);
425 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
436 //print('SCOPE-NAME:' + token.toString());
437 //print("DEAL WITH NAME:");
439 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
440 // skip anyting with "." before it..!!
442 if (this.ts.lookTok(-1).data == ".") {
443 // skip, it's an object prop.
444 //println("<i>"+token.data+"</i>");
447 //print("SYMBOL: " + token.toString());
450 if (symbol == 'this') {
453 if (this.mode == 'PASS2_SYMBOL_TREE') {
455 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
457 //print ("MUNGE?" + symbol);
459 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
461 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
462 identifier = this.getIdentifier(symbol, scope, token);
464 if (identifier == false) {
465 // BUG!find out where builtin is defined...
466 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
467 // Here, we found an undeclared and un-namespaced symbol that is
468 // 3 characters or less in length. Declare it in the global scope.
469 // We don't need to declare longer symbols since they won't cause
470 // any conflict with other munged symbols.
471 this.globalScope.declareIdentifier(symbol, token);
472 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
475 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
477 token.identifier = identifier;
478 identifier.refcount++;
483 //println("<B>SID</B>");
485 if (token.type != 'KEYW') {
488 //print('SCOPE-KEYW:' + token.toString());
489 // print("Check eval:");
493 if (this.mode == 'BUILDING_SYMBOL_TREE') {
495 if (token.name == "EVAL") {
497 //print(JSON.stringify(token, null,4));
498 // look back one and see if we can find a comment!!!
499 //if (this.ts.look(-1).type == "COMM") {
500 if (token.prefix && token.prefix.match(/eval/)) {
501 // look for eval:var:noreplace\n
504 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
505 //print("GOT: " + a);
506 var hi = _t.getIdentifier(a, scope, token);
507 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
509 // print("PROTECT "+a+" from munge");
510 //print(JSON.stringify(hi,null,4));
520 this.protectScopeFromObfuscation(scope);
521 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);
533 //print("parseScope TOK : " + token.toString());
534 token = this.ts.nextTok();
535 //if (this.ts.nextT()) break;
538 //print("<<< EXIT SCOPE");
539 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
543 parseExpression : function(scope) {
545 // Parse the expression until we encounter a comma or a semi-colon
546 // in the same brace nesting, bracket nesting and paren nesting.
547 // Parse functions if any...
548 //println("<i>EXP</i><BR/>");
549 !this.debug || print("PARSE EXPR");
552 // for printing stuff..
561 var expressionBraceNesting = this.braceNesting + 0;
562 var bracketNesting = 0;
563 var parensNesting = 0;
565 var isObjectLitAr = [ false ];
570 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
571 while ((token = this.ts.nextTok())) {
576 // moved out of loop?
577 currentScope = this.scopes[this.scopes.length-1];
579 var scopeIndent = '';
580 this.scopes.forEach(function() {
585 //this.dumpToken(token, this.scopes, this.braceNesting );
586 //print('EXPR' + token.toString());
589 //println("<i>"+token.data+"</i>");
590 //this.log("EXP:" + token.data);
591 switch (token.type) {
593 //print("EXPR-PUNC:" + token.toString());
598 //print("<< EXIT EXPRESSION");
606 case '(': //Token.LP:
607 case '{': //Token.LC:
608 case '[': //Token.LB:
609 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
610 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
611 //println("<i>"+token.data+"</i>");
615 for (var prop in token.props) {
616 if (!token.props[prop].val.length) {
617 print(JSON.stringify(token.props, null,4));
620 if (token.props[prop].val[0].data == 'function') {
621 // parse a function..
622 this.ts = new TokenStream(token.props[prop].val);
624 this.parseFunctionDeclaration(scope);
629 this.ts = new TokenStream(token.props[prop].val);
630 this.parseExpression(scope);
635 // it's an object literal..
636 // the values could be replaced..
642 token.items.forEach(function(expr) {
643 _this.ts = new TokenStream(expr);
644 _this.parseExpression(scope)
650 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
657 case ')': //Token.RP:
658 case ']': //Token.RB:
659 case '}': //Token.RB:
660 //print("<< EXIT EXPRESSION");
673 case 'STRN': // used for object lit detection..
674 //if (this.mode == 'BUILDING_SYMBOL_TREE')
675 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
683 if (this.mode == 'BUILDING_SYMBOL_TREE') {
685 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
687 //print("EXPR-NAME:" + token.toString());
690 //print("in NAME = " + token.toString());
691 //print("in NAME 0: " + this.ts.look(0).toString());
692 //print("in NAME 2: " + this.ts.lookTok(2).toString());
694 //print(this.ts.lookTok(-1).data);
696 if (this.ts.lookTok(-1).data == ".") {
700 if (symbol == 'this') {
704 if (this.mode == 'PASS2_SYMBOL_TREE') {
706 identifier = this.getIdentifier(symbol, scope, token);
707 //println("<B>??</B>");
708 if (identifier == false) {
710 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
711 // Here, we found an undeclared and un-namespaced symbol that is
712 // 3 characters or less in length. Declare it in the global scope.
713 // We don't need to declare longer symbols since they won't cause
714 // any conflict with other munged symbols.
715 this.globalScope.declareIdentifier(symbol, token);
716 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
717 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
720 //print("undeclared:" + token.toString())
725 //println("<B>++</B>");
726 token.identifier = identifier;
727 identifier.refcount++;
736 //println("<B>EID</B>");
738 //if (this.mode == 'BUILDING_SYMBOL_TREE')
739 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
741 //print('EXPR-KEYW:' + token.toString());
742 if (token.name == "FUNCTION") {
744 this.parseFunctionDeclaration(scope);
750 if (this.mode == 'BUILDING_SYMBOL_TREE') {
752 if (token.name == "EVAL") {
753 //print(JSON.stringify(token,null,4));
754 if (token.prefix && token.prefix.match(/eval:var:/g)) {
755 // look for eval:var:noreplace\n
756 // print("GOT MATCH?");
758 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
760 //print("PROTECT: " + a);
763 var hi = _t.getIdentifier(a, scope, token);
764 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
766 // println("PROTECT "+a+" from munge");
774 this.protectScopeFromObfuscation(scope);
775 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
783 //if (this.mode == 'BUILDING_SYMBOL_TREE')
784 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
789 //print("<< EXIT EXPRESSION");
794 parseCatch : function(scope) {
801 //token = getToken(-1);
802 //assert token.getType() == Token.CATCH;
803 token = this.ts.nextTok(1);
804 token = this.ts.nextTok(1);
807 //print(JSON.stringify(this.ts,null,4));
808 //assert token.getType() == Token.LP; (
809 //token = this.ts.nextTok();
810 //assert token.getType() == Token.NAME;
812 symbol = token.items[0][0].data;
815 if (this.mode == 'BUILDING_SYMBOL_TREE') {
816 // We must declare the exception identifier in the containing function
817 // scope to avoid errors related to the obfuscation process. No need to
818 // display a warning if the symbol was already declared here...
819 scope.declareIdentifier(symbol, token.items[0][0]);
821 //?? why inc the refcount?? - that should be set when building the tree???
822 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
823 identifier.refcount++;
826 //token = this.ts.nextTok();
827 //assert token.getType() == Token.RP; // )
830 parseFunctionDeclaration : function(scope)
832 //print("PARSE FUNCTION");
838 var b4braceNesting = this.braceNesting + 0;
840 //this.logR("<B>PARSING FUNCTION</B>");
843 token = this.ts.nextTok();
844 if (token.type == "NAME") {
845 if (this.mode == 'BUILDING_SYMBOL_TREE') {
846 // Get the name of the function and declare it in the current scope.
848 if (scope.getIdentifier(symbol,token) != false) {
849 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
851 scope.declareIdentifier(symbol,token);
853 token = this.ts.nextTok();
857 // return function() {....
858 while (token.data != "(") {
859 //print(token.toString());
860 token = this.ts.nextTok();
865 //assert token.getType() == Token.LP;
866 if (this.mode == 'BUILDING_SYMBOL_TREE') {
867 fnScope = new Scope(1, scope, token.n, '', token);
869 //println("STORING SCOPE" + this.ts.cursor);
871 this.indexedScopes[token.id] = fnScope;
874 //qln("FETCHING SCOPE" + this.ts.cursor);
875 fnScope = this.indexedScopes[token.id];
877 //if (this.mode == 'BUILDING_SYMBOL_TREE')
878 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
879 // Parse function arguments.
880 var args = token.items;
881 for (var argpos =0; argpos < args.length; argpos++) {
883 token = args[argpos][0];
884 //print ("FUNC ARGS: " + token.toString())
885 //assert token.getType() == Token.NAME ||
886 // token.getType() == Token.COMMA;
887 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
889 identifier = fnScope.declareIdentifier(symbol,token);
890 if (symbol == "$super" && argpos == 0) {
891 // Exception for Prototype 1.6...
892 identifier.preventMunging();
898 token = this.ts.nextTok();
899 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
901 //print(token.toString());
902 // assert token.getType() == Token.LC;
903 //this.braceNesting++;
905 //token = this.ts.nextTok();
906 //print(token.toString());
909 token.items.forEach(function(tar) {
910 _this.ts = new TokenStream(tar);
911 _this.parseScope(fnScope);
916 //print(JSON.stringify(this.ts,null,4));
917 //this.parseScope(fnScope);
919 // now pop it off the stack!!!
921 //this.braceNesting = b4braceNesting;
922 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
923 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
924 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
927 protectScopeFromObfuscation : function(scope) {
928 //assert scope != null;
930 if (scope == this.globalScope) {
931 // The global scope does not get obfuscated,
932 // so we don't need to worry about it...
936 // Find the highest local scope containing the specified scope.
937 while (scope && scope.parent != this.globalScope) {
938 scope = scope.parent;
941 //assert scope.getParentScope() == globalScope;
942 scope.preventMunging();
945 getIdentifier: function(symbol, scope, token) {
947 while (scope != false) {
948 identifier = scope.getIdentifier(symbol, token);
949 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
953 scope = scope.parent;