6 public class ScopeParser : Object {
9 Gee.ArrayList<string> warnings;
16 //mode : "", //"BUILDING_SYMBOL_TREE",
18 //indexedScopes : false,
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, '');
29 //this.timer = new Date() * 1;
102 //print('****************' + s);
103 this.warnings.add(s);
104 //println("WARNING:" + htmlescape(s) + "<BR>");
108 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
115 void buildSymbolTree()
120 this.braceNesting = 0;
122 // print(JSON.stringify(this.ts.tokens, null,4));
125 this.globalScope = new Scope(-1, false, -1, '');
126 this.indexedScopes = { 0 : this.globalScope };
128 this.mode = 'BUILDING_SYMBOL_TREE';
129 this.parseScope(this.globalScope);
131 //print("---------------END PASS 1 ---------------- ");
134 mungeSymboltree : function()
141 // One problem with obfuscation resides in the use of undeclared
142 // and un-namespaced global symbols that are 3 characters or less
143 // in length. Here is an example:
145 // var declaredGlobalVar;
147 // function declaredGlobalFn() {
149 // localvar = abc; // abc is an undeclared global symbol
152 // In the example above, there is a slim chance that localvar may be
153 // munged to 'abc', conflicting with the undeclared global symbol
154 // abc, creating a potential bug. The following code detects such
155 // global symbols. This must be done AFTER the entire file has been
156 // parsed, and BEFORE munging the symbol tree. Note that declaring
157 // extra symbols in the global scope won't hurt.
159 // Note: Since we go through all the tokens to do this, we also use
160 // the opportunity to count how many times each identifier is used.
163 this.braceNesting = 0;
164 this.mode = 'PASS2_SYMBOL_TREE';
166 //println("MUNGING?");
168 this.parseScope(this.globalScope);
170 //this.globalScope.dump();
173 this.globalScope.munge();
179 print (" ".substring(0, this.braceNesting*2) + str);
181 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
185 //println("<B>LOG:</B>" + str + "<BR/>");
192 parseScope : function(scope) // parse a token stream..
194 //this.timerPrint("parseScope EnterScope");
195 //this.log(">>> ENTER SCOPE" + this.scopes.length);
201 var expressionBraceNesting = this.braceNesting + 0;
203 var parensNesting = 0;
205 var isObjectLitAr = [ false ];
209 //var scopeIndent = '';
210 //this.scopes.forEach(function() {
211 // scopeIndent += ' ';
213 //print(">> ENTER SCOPE");
218 token = this.ts.lookTok(1);
220 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
221 //this.dumpToken(token , this.scopes, this.braceNesting);
222 //print('SCOPE:' + token.toString());
223 //this.log(token.data);
224 //if (token.type == 'NAME') {
225 // print('*' + token.data);
227 switch(token.type + '.' + token.name) {
229 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
230 //print('SCOPE-VAR:' + token.toString());
231 var vstart = this.ts.cursor +1;
233 //this.log("parseScope GOT VAR/CONST : " + token.toString());
235 token = this.ts.nextTok();
236 //!this.debug|| print( token.toString());
237 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
238 if (!token) { // can return false at EOF!
241 if (token.name == "VAR" || token.data == ',') { // kludge..
244 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
245 if (token.type != "NAME") {
246 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
247 print(this.ts.tokens[i].toString());
250 print( "var without ident");
255 if (this.mode == "BUILDING_SYMBOL_TREE") {
256 identifier = scope.getIdentifier(token.data,token) ;
258 if (identifier == false) {
259 scope.declareIdentifier(token.data, token);
261 token.identifier = identifier;
262 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
266 token = this.ts.nextTok();
267 !this.debug|| print(token.toString());
269 assert token.getType() == Token.SEMI ||
270 token.getType() == Token.ASSIGN ||
271 token.getType() == Token.COMMA ||
272 token.getType() == Token.IN;
274 if (token.name == "IN") {
277 //var bn = this.braceNesting;
278 var bn = this.braceNesting;
281 if (!token || token.type == 'VOID' || token.data == ',') {
285 token = this.ts.nextTok();
289 this.ts = new TokenStream(nts);
290 this.parseExpression(scope);
294 this.braceNesting = bn;
295 //this.braceNesting = bn;
296 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
298 token = this.ts.lookTok(1);
300 // print("AFTER EXP: " + token.toString());
301 if (token.data == ';') {
308 //this.ts.dump(vstart , this.ts.cursor);
313 case "KEYW.FUNCTION":
314 //if (this.mode == 'BUILDING_SYMBOL_TREE')
315 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
316 //println("<i>"+token.data+"</i>");
317 var bn = this.braceNesting;
318 this.parseFunctionDeclaration(scope);
319 this.braceNesting = bn;
322 case "PUNC.LEFT_CURLY": // {
323 case "PUNC.LEFT_PAREN": // (
324 case "PUNC.LEFT_BRACE": // [
325 //print('SCOPE-CURLY/PAREN:' + token.toString());
326 //println("<i>"+token.data+"</i>");
330 // { a : ... , c : .... }
332 for (var prop in token.props) {
335 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
336 if (token.props[prop].val[0].data == 'function') {
337 // parse a function..
338 this.ts = new TokenStream(token.props[prop].val);
340 this.parseFunctionDeclaration(scope);
346 this.ts = new TokenStream(token.props[prop].val);
347 this.parseExpression(scope);
352 // it's an object literal..
353 // the values could be replaced..
357 // ( ... ) or { .... } not object literals..
360 for (var xx =0; xx < token.items.length; xx++) {
361 expr = token.items[xx];
362 //token.items.forEach(function(expr) {
363 //print(expr.toString());
364 _this.ts = new TokenStream(expr);
365 //if (curTS.data == '(') {
366 _this.parseScope(scope)
368 // _this.parseExpression(scope)
373 //print("NOT PROPS"); Seed.quit();
375 //isObjectLitAr.push(false);
376 //this.braceNesting++;
378 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
381 case "PUNC.RIGHT_CURLY": // }
382 //print("<< EXIT SCOPE");
386 //print('SCOPE-WITH:' + token.toString());
387 //println("<i>"+token.data+"</i>");
388 if (this.mode == "BUILDING_SYMBOL_TREE") {
389 // Inside a 'with' block, it is impossible to figure out
390 // statically whether a symbol is a local variable or an
391 // object member. As a consequence, the only thing we can
392 // do is turn the obfuscation off for the highest scope
393 // containing the 'with' block.
394 this.protectScopeFromObfuscation(scope);
395 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
400 //print('SCOPE-CATCH:' + token.toString());
401 //println("<i>"+token.data+"</i>");
402 this.parseCatch(scope);
405 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
406 case "STRN.SINGLE_QUOTE":
407 // print('SCOPE-STRING:' + token.toString());
408 //println("<i>"+token.data+"</i>");
410 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
411 // then we are in an object lit.. -> we need to flag the brace as such...
413 isObjectLitAr.push(true);
414 //print(">>>>>> OBJLIT REPUSH(true)");
416 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
418 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
419 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
420 // see if we can replace..
421 // remove the quotes..
422 // should do a bit more checking!!!! (what about wierd char's in the string..
423 var str = token.data.substring(1,token.data.length-1);
424 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
435 //print('SCOPE-NAME:' + token.toString());
436 //print("DEAL WITH NAME:");
438 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
439 // skip anyting with "." before it..!!
441 if (this.ts.lookTok(-1).data == ".") {
442 // skip, it's an object prop.
443 //println("<i>"+token.data+"</i>");
446 //print("SYMBOL: " + token.toString());
449 if (symbol == 'this') {
452 if (this.mode == 'PASS2_SYMBOL_TREE') {
454 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
456 //print ("MUNGE?" + symbol);
458 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
460 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
461 identifier = this.getIdentifier(symbol, scope, token);
463 if (identifier == false) {
464 // BUG!find out where builtin is defined...
465 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
466 // Here, we found an undeclared and un-namespaced symbol that is
467 // 3 characters or less in length. Declare it in the global scope.
468 // We don't need to declare longer symbols since they won't cause
469 // any conflict with other munged symbols.
470 this.globalScope.declareIdentifier(symbol, token);
471 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
474 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
476 token.identifier = identifier;
477 identifier.refcount++;
482 //println("<B>SID</B>");
484 if (token.type != 'KEYW') {
487 //print('SCOPE-KEYW:' + token.toString());
488 // print("Check eval:");
492 if (this.mode == 'BUILDING_SYMBOL_TREE') {
494 if (token.name == "EVAL") {
496 //print(JSON.stringify(token, null,4));
497 // look back one and see if we can find a comment!!!
498 //if (this.ts.look(-1).type == "COMM") {
499 if (token.prefix && token.prefix.match(/eval/)) {
500 // look for eval:var:noreplace\n
503 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
504 //print("GOT: " + a);
505 var hi = _t.getIdentifier(a, scope, token);
506 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
508 // print("PROTECT "+a+" from munge");
509 //print(JSON.stringify(hi,null,4));
519 this.protectScopeFromObfuscation(scope);
520 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);
532 //print("parseScope TOK : " + token.toString());
533 token = this.ts.nextTok();
534 //if (this.ts.nextT()) break;
537 //print("<<< EXIT SCOPE");
538 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
542 parseExpression : function(scope) {
544 // Parse the expression until we encounter a comma or a semi-colon
545 // in the same brace nesting, bracket nesting and paren nesting.
546 // Parse functions if any...
547 //println("<i>EXP</i><BR/>");
548 !this.debug || print("PARSE EXPR");
551 // for printing stuff..
560 var expressionBraceNesting = this.braceNesting + 0;
561 var bracketNesting = 0;
562 var parensNesting = 0;
564 var isObjectLitAr = [ false ];
569 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
570 while ((token = this.ts.nextTok())) {
575 // moved out of loop?
576 currentScope = this.scopes[this.scopes.length-1];
578 var scopeIndent = '';
579 this.scopes.forEach(function() {
584 //this.dumpToken(token, this.scopes, this.braceNesting );
585 //print('EXPR' + token.toString());
588 //println("<i>"+token.data+"</i>");
589 //this.log("EXP:" + token.data);
590 switch (token.type) {
592 //print("EXPR-PUNC:" + token.toString());
597 //print("<< EXIT EXPRESSION");
605 case '(': //Token.LP:
606 case '{': //Token.LC:
607 case '[': //Token.LB:
608 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
609 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
610 //println("<i>"+token.data+"</i>");
614 for (var prop in token.props) {
615 if (!token.props[prop].val.length) {
616 print(JSON.stringify(token.props, null,4));
619 if (token.props[prop].val[0].data == 'function') {
620 // parse a function..
621 this.ts = new TokenStream(token.props[prop].val);
623 this.parseFunctionDeclaration(scope);
628 this.ts = new TokenStream(token.props[prop].val);
629 this.parseExpression(scope);
634 // it's an object literal..
635 // the values could be replaced..
641 token.items.forEach(function(expr) {
642 _this.ts = new TokenStream(expr);
643 _this.parseExpression(scope)
649 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
656 case ')': //Token.RP:
657 case ']': //Token.RB:
658 case '}': //Token.RB:
659 //print("<< EXIT EXPRESSION");
672 case 'STRN': // used for object lit detection..
673 //if (this.mode == 'BUILDING_SYMBOL_TREE')
674 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
682 if (this.mode == 'BUILDING_SYMBOL_TREE') {
684 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
686 //print("EXPR-NAME:" + token.toString());
689 //print("in NAME = " + token.toString());
690 //print("in NAME 0: " + this.ts.look(0).toString());
691 //print("in NAME 2: " + this.ts.lookTok(2).toString());
693 //print(this.ts.lookTok(-1).data);
695 if (this.ts.lookTok(-1).data == ".") {
699 if (symbol == 'this') {
703 if (this.mode == 'PASS2_SYMBOL_TREE') {
705 identifier = this.getIdentifier(symbol, scope, token);
706 //println("<B>??</B>");
707 if (identifier == false) {
709 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
710 // Here, we found an undeclared and un-namespaced symbol that is
711 // 3 characters or less in length. Declare it in the global scope.
712 // We don't need to declare longer symbols since they won't cause
713 // any conflict with other munged symbols.
714 this.globalScope.declareIdentifier(symbol, token);
715 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
716 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
719 //print("undeclared:" + token.toString())
724 //println("<B>++</B>");
725 token.identifier = identifier;
726 identifier.refcount++;
735 //println("<B>EID</B>");
737 //if (this.mode == 'BUILDING_SYMBOL_TREE')
738 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
740 //print('EXPR-KEYW:' + token.toString());
741 if (token.name == "FUNCTION") {
743 this.parseFunctionDeclaration(scope);
749 if (this.mode == 'BUILDING_SYMBOL_TREE') {
751 if (token.name == "EVAL") {
752 //print(JSON.stringify(token,null,4));
753 if (token.prefix && token.prefix.match(/eval:var:/g)) {
754 // look for eval:var:noreplace\n
755 // print("GOT MATCH?");
757 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
759 //print("PROTECT: " + a);
762 var hi = _t.getIdentifier(a, scope, token);
763 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
765 // println("PROTECT "+a+" from munge");
773 this.protectScopeFromObfuscation(scope);
774 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
782 //if (this.mode == 'BUILDING_SYMBOL_TREE')
783 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
788 //print("<< EXIT EXPRESSION");
793 parseCatch : function(scope) {
800 //token = getToken(-1);
801 //assert token.getType() == Token.CATCH;
802 token = this.ts.nextTok(1);
803 token = this.ts.nextTok(1);
806 //print(JSON.stringify(this.ts,null,4));
807 //assert token.getType() == Token.LP; (
808 //token = this.ts.nextTok();
809 //assert token.getType() == Token.NAME;
811 symbol = token.items[0][0].data;
814 if (this.mode == 'BUILDING_SYMBOL_TREE') {
815 // We must declare the exception identifier in the containing function
816 // scope to avoid errors related to the obfuscation process. No need to
817 // display a warning if the symbol was already declared here...
818 scope.declareIdentifier(symbol, token.items[0][0]);
820 //?? why inc the refcount?? - that should be set when building the tree???
821 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
822 identifier.refcount++;
825 //token = this.ts.nextTok();
826 //assert token.getType() == Token.RP; // )
829 parseFunctionDeclaration : function(scope)
831 //print("PARSE FUNCTION");
837 var b4braceNesting = this.braceNesting + 0;
839 //this.logR("<B>PARSING FUNCTION</B>");
842 token = this.ts.nextTok();
843 if (token.type == "NAME") {
844 if (this.mode == 'BUILDING_SYMBOL_TREE') {
845 // Get the name of the function and declare it in the current scope.
847 if (scope.getIdentifier(symbol,token) != false) {
848 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
850 scope.declareIdentifier(symbol,token);
852 token = this.ts.nextTok();
856 // return function() {....
857 while (token.data != "(") {
858 //print(token.toString());
859 token = this.ts.nextTok();
864 //assert token.getType() == Token.LP;
865 if (this.mode == 'BUILDING_SYMBOL_TREE') {
866 fnScope = new Scope(1, scope, token.n, '', token);
868 //println("STORING SCOPE" + this.ts.cursor);
870 this.indexedScopes[token.id] = fnScope;
873 //qln("FETCHING SCOPE" + this.ts.cursor);
874 fnScope = this.indexedScopes[token.id];
876 //if (this.mode == 'BUILDING_SYMBOL_TREE')
877 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
878 // Parse function arguments.
879 var args = token.items;
880 for (var argpos =0; argpos < args.length; argpos++) {
882 token = args[argpos][0];
883 //print ("FUNC ARGS: " + token.toString())
884 //assert token.getType() == Token.NAME ||
885 // token.getType() == Token.COMMA;
886 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
888 identifier = fnScope.declareIdentifier(symbol,token);
889 if (symbol == "$super" && argpos == 0) {
890 // Exception for Prototype 1.6...
891 identifier.preventMunging();
897 token = this.ts.nextTok();
898 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
900 //print(token.toString());
901 // assert token.getType() == Token.LC;
902 //this.braceNesting++;
904 //token = this.ts.nextTok();
905 //print(token.toString());
908 token.items.forEach(function(tar) {
909 _this.ts = new TokenStream(tar);
910 _this.parseScope(fnScope);
915 //print(JSON.stringify(this.ts,null,4));
916 //this.parseScope(fnScope);
918 // now pop it off the stack!!!
920 //this.braceNesting = b4braceNesting;
921 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
922 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
923 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
926 protectScopeFromObfuscation : function(scope) {
927 //assert scope != null;
929 if (scope == this.globalScope) {
930 // The global scope does not get obfuscated,
931 // so we don't need to worry about it...
935 // Find the highest local scope containing the specified scope.
936 while (scope && scope.parent != this.globalScope) {
937 scope = scope.parent;
940 //assert scope.getParentScope() == globalScope;
941 scope.preventMunging();
944 getIdentifier: function(symbol, scope, token) {
946 while (scope != false) {
947 identifier = scope.getIdentifier(symbol, token);
948 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
952 scope = scope.parent;