6 public enum ScopeParserMode {
12 public class ScopeParser : Object {
15 Gee.ArrayList<string> warnings;
24 Gee.HashMap<int,Scope> indexedScopes;
29 public ScopeParser(TokenStream ts) {
30 this.ts = ts; // {TokenStream}
31 this.warnings = new Gee.ArrayList<string>();
32 this.globalScope = new Scope(-1, false, -1, '');
33 this.indexedScopes = new Gee.HashMap<int,Scope>();
36 //this.timer = new Date() * 1;
109 //print('****************' + s);
110 this.warnings.add(s);
111 //println("WARNING:" + htmlescape(s) + "<BR>");
115 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
122 void buildSymbolTree()
127 this.braceNesting = 0;
129 // print(JSON.stringify(this.ts.tokens, null,4));
132 this.globalScope = new Scope(-1, false, -1, '');
133 this.indexedScopes = new Gee.HashMap<int,Scope>();
134 this.indexedScopes.set(0, this.globalScope );
136 this.mode = ScopeParserMode.BUILDING_SYMBOL_TREE;
138 this.parseScope(this.globalScope);
140 //print("---------------END PASS 1 ---------------- ");
144 void mungeSymboltree()
151 // One problem with obfuscation resides in the use of undeclared
152 // and un-namespaced global symbols that are 3 characters or less
153 // in length. Here is an example:
155 // var declaredGlobalVar;
157 // function declaredGlobalFn() {
159 // localvar = abc; // abc is an undeclared global symbol
162 // In the example above, there is a slim chance that localvar may be
163 // munged to 'abc', conflicting with the undeclared global symbol
164 // abc, creating a potential bug. The following code detects such
165 // global symbols. This must be done AFTER the entire file has been
166 // parsed, and BEFORE munging the symbol tree. Note that declaring
167 // extra symbols in the global scope won't hurt.
169 // Note: Since we go through all the tokens to do this, we also use
170 // the opportunity to count how many times each identifier is used.
173 this.braceNesting = 0;
174 this.mode = ScopeParserMode.PASS2_SYMBOL_TREE;
176 //println("MUNGING?");
178 this.parseScope(this.globalScope);
180 //this.globalScope.dump();
183 this.globalScope.munge();
190 //print (" ".substring(0, this.braceNesting*2) + str);
192 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
194 void logR (string str)
196 //println("<B>LOG:</B>" + str + "<BR/>");
203 void parseScope(Scope scope) // parse a token stream..
205 //this.timerPrint("parseScope EnterScope");
206 //this.log(">>> ENTER SCOPE" + this.scopes.length);
212 var expressionBraceNesting = this.braceNesting + 0;
214 var parensNesting = 0;
216 var isObjectLitAr = [ false ];
220 //var scopeIndent = '';
221 //this.scopes.forEach(function() {
222 // scopeIndent += ' ';
224 //print(">> ENTER SCOPE");
229 token = this.ts.lookTok(1);
231 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
232 //this.dumpToken(token , this.scopes, this.braceNesting);
233 //print('SCOPE:' + token.toString());
234 //this.log(token.data);
235 //if (token.type == 'NAME') {
236 // print('*' + token.data);
238 switch(token.type + '.' + token.name) {
240 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
241 //print('SCOPE-VAR:' + token.toString());
242 var vstart = this.ts.cursor +1;
244 //this.log("parseScope GOT VAR/CONST : " + token.toString());
246 token = this.ts.nextTok();
247 //!this.debug|| print( token.toString());
248 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
249 if (!token) { // can return false at EOF!
252 if (token.name == "VAR" || token.data == ',') { // kludge..
255 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
256 if (token.type != "NAME") {
257 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
258 print(this.ts.tokens[i].toString());
261 print( "var without ident");
266 if (this.mode == "BUILDING_SYMBOL_TREE") {
267 identifier = scope.getIdentifier(token.data,token) ;
269 if (identifier == false) {
270 scope.declareIdentifier(token.data, token);
272 token.identifier = identifier;
273 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
277 token = this.ts.nextTok();
278 !this.debug|| print(token.toString());
280 assert token.getType() == Token.SEMI ||
281 token.getType() == Token.ASSIGN ||
282 token.getType() == Token.COMMA ||
283 token.getType() == Token.IN;
285 if (token.name == "IN") {
288 //var bn = this.braceNesting;
289 var bn = this.braceNesting;
292 if (!token || token.type == 'VOID' || token.data == ',') {
296 token = this.ts.nextTok();
300 this.ts = new TokenStream(nts);
301 this.parseExpression(scope);
305 this.braceNesting = bn;
306 //this.braceNesting = bn;
307 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
309 token = this.ts.lookTok(1);
311 // print("AFTER EXP: " + token.toString());
312 if (token.data == ';') {
319 //this.ts.dump(vstart , this.ts.cursor);
324 case "KEYW.FUNCTION":
325 //if (this.mode == 'BUILDING_SYMBOL_TREE')
326 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
327 //println("<i>"+token.data+"</i>");
328 var bn = this.braceNesting;
329 this.parseFunctionDeclaration(scope);
330 this.braceNesting = bn;
333 case "PUNC.LEFT_CURLY": // {
334 case "PUNC.LEFT_PAREN": // (
335 case "PUNC.LEFT_BRACE": // [
336 //print('SCOPE-CURLY/PAREN:' + token.toString());
337 //println("<i>"+token.data+"</i>");
341 // { a : ... , c : .... }
343 for (var prop in token.props) {
346 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
347 if (token.props[prop].val[0].data == 'function') {
348 // parse a function..
349 this.ts = new TokenStream(token.props[prop].val);
351 this.parseFunctionDeclaration(scope);
357 this.ts = new TokenStream(token.props[prop].val);
358 this.parseExpression(scope);
363 // it's an object literal..
364 // the values could be replaced..
368 // ( ... ) or { .... } not object literals..
371 for (var xx =0; xx < token.items.length; xx++) {
372 expr = token.items[xx];
373 //token.items.forEach(function(expr) {
374 //print(expr.toString());
375 _this.ts = new TokenStream(expr);
376 //if (curTS.data == '(') {
377 _this.parseScope(scope)
379 // _this.parseExpression(scope)
384 //print("NOT PROPS"); Seed.quit();
386 //isObjectLitAr.push(false);
387 //this.braceNesting++;
389 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
392 case "PUNC.RIGHT_CURLY": // }
393 //print("<< EXIT SCOPE");
397 //print('SCOPE-WITH:' + token.toString());
398 //println("<i>"+token.data+"</i>");
399 if (this.mode == "BUILDING_SYMBOL_TREE") {
400 // Inside a 'with' block, it is impossible to figure out
401 // statically whether a symbol is a local variable or an
402 // object member. As a consequence, the only thing we can
403 // do is turn the obfuscation off for the highest scope
404 // containing the 'with' block.
405 this.protectScopeFromObfuscation(scope);
406 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
411 //print('SCOPE-CATCH:' + token.toString());
412 //println("<i>"+token.data+"</i>");
413 this.parseCatch(scope);
416 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
417 case "STRN.SINGLE_QUOTE":
418 // print('SCOPE-STRING:' + token.toString());
419 //println("<i>"+token.data+"</i>");
421 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
422 // then we are in an object lit.. -> we need to flag the brace as such...
424 isObjectLitAr.push(true);
425 //print(">>>>>> OBJLIT REPUSH(true)");
427 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
429 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
430 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
431 // see if we can replace..
432 // remove the quotes..
433 // should do a bit more checking!!!! (what about wierd char's in the string..
434 var str = token.data.substring(1,token.data.length-1);
435 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
446 //print('SCOPE-NAME:' + token.toString());
447 //print("DEAL WITH NAME:");
449 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
450 // skip anyting with "." before it..!!
452 if (this.ts.lookTok(-1).data == ".") {
453 // skip, it's an object prop.
454 //println("<i>"+token.data+"</i>");
457 //print("SYMBOL: " + token.toString());
460 if (symbol == 'this') {
463 if (this.mode == 'PASS2_SYMBOL_TREE') {
465 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
467 //print ("MUNGE?" + symbol);
469 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
471 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
472 identifier = this.getIdentifier(symbol, scope, token);
474 if (identifier == false) {
475 // BUG!find out where builtin is defined...
476 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
477 // Here, we found an undeclared and un-namespaced symbol that is
478 // 3 characters or less in length. Declare it in the global scope.
479 // We don't need to declare longer symbols since they won't cause
480 // any conflict with other munged symbols.
481 this.globalScope.declareIdentifier(symbol, token);
482 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
485 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
487 token.identifier = identifier;
488 identifier.refcount++;
493 //println("<B>SID</B>");
495 if (token.type != 'KEYW') {
498 //print('SCOPE-KEYW:' + token.toString());
499 // print("Check eval:");
503 if (this.mode == 'BUILDING_SYMBOL_TREE') {
505 if (token.name == "EVAL") {
507 //print(JSON.stringify(token, null,4));
508 // look back one and see if we can find a comment!!!
509 //if (this.ts.look(-1).type == "COMM") {
510 if (token.prefix && token.prefix.match(/eval/)) {
511 // look for eval:var:noreplace\n
514 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
515 //print("GOT: " + a);
516 var hi = _t.getIdentifier(a, scope, token);
517 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
519 // print("PROTECT "+a+" from munge");
520 //print(JSON.stringify(hi,null,4));
530 this.protectScopeFromObfuscation(scope);
531 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);
543 //print("parseScope TOK : " + token.toString());
544 token = this.ts.nextTok();
545 //if (this.ts.nextT()) break;
548 //print("<<< EXIT SCOPE");
549 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
553 parseExpression : function(scope) {
555 // Parse the expression until we encounter a comma or a semi-colon
556 // in the same brace nesting, bracket nesting and paren nesting.
557 // Parse functions if any...
558 //println("<i>EXP</i><BR/>");
559 !this.debug || print("PARSE EXPR");
562 // for printing stuff..
571 var expressionBraceNesting = this.braceNesting + 0;
572 var bracketNesting = 0;
573 var parensNesting = 0;
575 var isObjectLitAr = [ false ];
580 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
581 while ((token = this.ts.nextTok())) {
586 // moved out of loop?
587 currentScope = this.scopes[this.scopes.length-1];
589 var scopeIndent = '';
590 this.scopes.forEach(function() {
595 //this.dumpToken(token, this.scopes, this.braceNesting );
596 //print('EXPR' + token.toString());
599 //println("<i>"+token.data+"</i>");
600 //this.log("EXP:" + token.data);
601 switch (token.type) {
603 //print("EXPR-PUNC:" + token.toString());
608 //print("<< EXIT EXPRESSION");
616 case '(': //Token.LP:
617 case '{': //Token.LC:
618 case '[': //Token.LB:
619 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
620 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
621 //println("<i>"+token.data+"</i>");
625 for (var prop in token.props) {
626 if (!token.props[prop].val.length) {
627 print(JSON.stringify(token.props, null,4));
630 if (token.props[prop].val[0].data == 'function') {
631 // parse a function..
632 this.ts = new TokenStream(token.props[prop].val);
634 this.parseFunctionDeclaration(scope);
639 this.ts = new TokenStream(token.props[prop].val);
640 this.parseExpression(scope);
645 // it's an object literal..
646 // the values could be replaced..
652 token.items.forEach(function(expr) {
653 _this.ts = new TokenStream(expr);
654 _this.parseExpression(scope)
660 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
667 case ')': //Token.RP:
668 case ']': //Token.RB:
669 case '}': //Token.RB:
670 //print("<< EXIT EXPRESSION");
683 case 'STRN': // used for object lit detection..
684 //if (this.mode == 'BUILDING_SYMBOL_TREE')
685 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
693 if (this.mode == 'BUILDING_SYMBOL_TREE') {
695 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
697 //print("EXPR-NAME:" + token.toString());
700 //print("in NAME = " + token.toString());
701 //print("in NAME 0: " + this.ts.look(0).toString());
702 //print("in NAME 2: " + this.ts.lookTok(2).toString());
704 //print(this.ts.lookTok(-1).data);
706 if (this.ts.lookTok(-1).data == ".") {
710 if (symbol == 'this') {
714 if (this.mode == 'PASS2_SYMBOL_TREE') {
716 identifier = this.getIdentifier(symbol, scope, token);
717 //println("<B>??</B>");
718 if (identifier == false) {
720 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
721 // Here, we found an undeclared and un-namespaced symbol that is
722 // 3 characters or less in length. Declare it in the global scope.
723 // We don't need to declare longer symbols since they won't cause
724 // any conflict with other munged symbols.
725 this.globalScope.declareIdentifier(symbol, token);
726 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
727 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
730 //print("undeclared:" + token.toString())
735 //println("<B>++</B>");
736 token.identifier = identifier;
737 identifier.refcount++;
746 //println("<B>EID</B>");
748 //if (this.mode == 'BUILDING_SYMBOL_TREE')
749 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
751 //print('EXPR-KEYW:' + token.toString());
752 if (token.name == "FUNCTION") {
754 this.parseFunctionDeclaration(scope);
760 if (this.mode == 'BUILDING_SYMBOL_TREE') {
762 if (token.name == "EVAL") {
763 //print(JSON.stringify(token,null,4));
764 if (token.prefix && token.prefix.match(/eval:var:/g)) {
765 // look for eval:var:noreplace\n
766 // print("GOT MATCH?");
768 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
770 //print("PROTECT: " + a);
773 var hi = _t.getIdentifier(a, scope, token);
774 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
776 // println("PROTECT "+a+" from munge");
784 this.protectScopeFromObfuscation(scope);
785 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
793 //if (this.mode == 'BUILDING_SYMBOL_TREE')
794 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
799 //print("<< EXIT EXPRESSION");
804 parseCatch : function(scope) {
811 //token = getToken(-1);
812 //assert token.getType() == Token.CATCH;
813 token = this.ts.nextTok(1);
814 token = this.ts.nextTok(1);
817 //print(JSON.stringify(this.ts,null,4));
818 //assert token.getType() == Token.LP; (
819 //token = this.ts.nextTok();
820 //assert token.getType() == Token.NAME;
822 symbol = token.items[0][0].data;
825 if (this.mode == 'BUILDING_SYMBOL_TREE') {
826 // We must declare the exception identifier in the containing function
827 // scope to avoid errors related to the obfuscation process. No need to
828 // display a warning if the symbol was already declared here...
829 scope.declareIdentifier(symbol, token.items[0][0]);
831 //?? why inc the refcount?? - that should be set when building the tree???
832 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
833 identifier.refcount++;
836 //token = this.ts.nextTok();
837 //assert token.getType() == Token.RP; // )
840 parseFunctionDeclaration : function(scope)
842 //print("PARSE FUNCTION");
848 var b4braceNesting = this.braceNesting + 0;
850 //this.logR("<B>PARSING FUNCTION</B>");
853 token = this.ts.nextTok();
854 if (token.type == "NAME") {
855 if (this.mode == 'BUILDING_SYMBOL_TREE') {
856 // Get the name of the function and declare it in the current scope.
858 if (scope.getIdentifier(symbol,token) != false) {
859 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
861 scope.declareIdentifier(symbol,token);
863 token = this.ts.nextTok();
867 // return function() {....
868 while (token.data != "(") {
869 //print(token.toString());
870 token = this.ts.nextTok();
875 //assert token.getType() == Token.LP;
876 if (this.mode == 'BUILDING_SYMBOL_TREE') {
877 fnScope = new Scope(1, scope, token.n, '', token);
879 //println("STORING SCOPE" + this.ts.cursor);
881 this.indexedScopes[token.id] = fnScope;
884 //qln("FETCHING SCOPE" + this.ts.cursor);
885 fnScope = this.indexedScopes[token.id];
887 //if (this.mode == 'BUILDING_SYMBOL_TREE')
888 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
889 // Parse function arguments.
890 var args = token.items;
891 for (var argpos =0; argpos < args.length; argpos++) {
893 token = args[argpos][0];
894 //print ("FUNC ARGS: " + token.toString())
895 //assert token.getType() == Token.NAME ||
896 // token.getType() == Token.COMMA;
897 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
899 identifier = fnScope.declareIdentifier(symbol,token);
900 if (symbol == "$super" && argpos == 0) {
901 // Exception for Prototype 1.6...
902 identifier.preventMunging();
908 token = this.ts.nextTok();
909 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
911 //print(token.toString());
912 // assert token.getType() == Token.LC;
913 //this.braceNesting++;
915 //token = this.ts.nextTok();
916 //print(token.toString());
919 token.items.forEach(function(tar) {
920 _this.ts = new TokenStream(tar);
921 _this.parseScope(fnScope);
926 //print(JSON.stringify(this.ts,null,4));
927 //this.parseScope(fnScope);
929 // now pop it off the stack!!!
931 //this.braceNesting = b4braceNesting;
932 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
933 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
934 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
937 protectScopeFromObfuscation : function(scope) {
938 //assert scope != null;
940 if (scope == this.globalScope) {
941 // The global scope does not get obfuscated,
942 // so we don't need to worry about it...
946 // Find the highest local scope containing the specified scope.
947 while (scope && scope.parent != this.globalScope) {
948 scope = scope.parent;
951 //assert scope.getParentScope() == globalScope;
952 scope.preventMunging();
955 getIdentifier: function(symbol, scope, token) {
957 while (scope != false) {
958 identifier = scope.getIdentifier(symbol, token);
959 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
963 scope = scope.parent;