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>();
27 //this.timer = new Date() * 1;
100 //print('****************' + s);
101 this.warnings.add(s);
102 //println("WARNING:" + htmlescape(s) + "<BR>");
106 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
113 buildSymbolTree : function()
118 this.braceNesting = 0;
120 // print(JSON.stringify(this.ts.tokens, null,4));
123 this.globalScope = new Scope(-1, false, -1, '');
124 this.indexedScopes = { 0 : this.globalScope };
126 this.mode = 'BUILDING_SYMBOL_TREE';
127 this.parseScope(this.globalScope);
129 //print("---------------END PASS 1 ---------------- ");
132 mungeSymboltree : function()
139 // One problem with obfuscation resides in the use of undeclared
140 // and un-namespaced global symbols that are 3 characters or less
141 // in length. Here is an example:
143 // var declaredGlobalVar;
145 // function declaredGlobalFn() {
147 // localvar = abc; // abc is an undeclared global symbol
150 // In the example above, there is a slim chance that localvar may be
151 // munged to 'abc', conflicting with the undeclared global symbol
152 // abc, creating a potential bug. The following code detects such
153 // global symbols. This must be done AFTER the entire file has been
154 // parsed, and BEFORE munging the symbol tree. Note that declaring
155 // extra symbols in the global scope won't hurt.
157 // Note: Since we go through all the tokens to do this, we also use
158 // the opportunity to count how many times each identifier is used.
161 this.braceNesting = 0;
162 this.mode = 'PASS2_SYMBOL_TREE';
164 //println("MUNGING?");
166 this.parseScope(this.globalScope);
168 //this.globalScope.dump();
171 this.globalScope.munge();
177 print (" ".substring(0, this.braceNesting*2) + str);
179 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
183 //println("<B>LOG:</B>" + str + "<BR/>");
190 parseScope : function(scope) // parse a token stream..
192 //this.timerPrint("parseScope EnterScope");
193 //this.log(">>> ENTER SCOPE" + this.scopes.length);
199 var expressionBraceNesting = this.braceNesting + 0;
201 var parensNesting = 0;
203 var isObjectLitAr = [ false ];
207 //var scopeIndent = '';
208 //this.scopes.forEach(function() {
209 // scopeIndent += ' ';
211 //print(">> ENTER SCOPE");
216 token = this.ts.lookTok(1);
218 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
219 //this.dumpToken(token , this.scopes, this.braceNesting);
220 //print('SCOPE:' + token.toString());
221 //this.log(token.data);
222 //if (token.type == 'NAME') {
223 // print('*' + token.data);
225 switch(token.type + '.' + token.name) {
227 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
228 //print('SCOPE-VAR:' + token.toString());
229 var vstart = this.ts.cursor +1;
231 //this.log("parseScope GOT VAR/CONST : " + token.toString());
233 token = this.ts.nextTok();
234 //!this.debug|| print( token.toString());
235 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
236 if (!token) { // can return false at EOF!
239 if (token.name == "VAR" || token.data == ',') { // kludge..
242 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
243 if (token.type != "NAME") {
244 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
245 print(this.ts.tokens[i].toString());
248 print( "var without ident");
253 if (this.mode == "BUILDING_SYMBOL_TREE") {
254 identifier = scope.getIdentifier(token.data,token) ;
256 if (identifier == false) {
257 scope.declareIdentifier(token.data, token);
259 token.identifier = identifier;
260 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
264 token = this.ts.nextTok();
265 !this.debug|| print(token.toString());
267 assert token.getType() == Token.SEMI ||
268 token.getType() == Token.ASSIGN ||
269 token.getType() == Token.COMMA ||
270 token.getType() == Token.IN;
272 if (token.name == "IN") {
275 //var bn = this.braceNesting;
276 var bn = this.braceNesting;
279 if (!token || token.type == 'VOID' || token.data == ',') {
283 token = this.ts.nextTok();
287 this.ts = new TokenStream(nts);
288 this.parseExpression(scope);
292 this.braceNesting = bn;
293 //this.braceNesting = bn;
294 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
296 token = this.ts.lookTok(1);
298 // print("AFTER EXP: " + token.toString());
299 if (token.data == ';') {
306 //this.ts.dump(vstart , this.ts.cursor);
311 case "KEYW.FUNCTION":
312 //if (this.mode == 'BUILDING_SYMBOL_TREE')
313 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
314 //println("<i>"+token.data+"</i>");
315 var bn = this.braceNesting;
316 this.parseFunctionDeclaration(scope);
317 this.braceNesting = bn;
320 case "PUNC.LEFT_CURLY": // {
321 case "PUNC.LEFT_PAREN": // (
322 case "PUNC.LEFT_BRACE": // [
323 //print('SCOPE-CURLY/PAREN:' + token.toString());
324 //println("<i>"+token.data+"</i>");
328 // { a : ... , c : .... }
330 for (var prop in token.props) {
333 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
334 if (token.props[prop].val[0].data == 'function') {
335 // parse a function..
336 this.ts = new TokenStream(token.props[prop].val);
338 this.parseFunctionDeclaration(scope);
344 this.ts = new TokenStream(token.props[prop].val);
345 this.parseExpression(scope);
350 // it's an object literal..
351 // the values could be replaced..
355 // ( ... ) or { .... } not object literals..
358 for (var xx =0; xx < token.items.length; xx++) {
359 expr = token.items[xx];
360 //token.items.forEach(function(expr) {
361 //print(expr.toString());
362 _this.ts = new TokenStream(expr);
363 //if (curTS.data == '(') {
364 _this.parseScope(scope)
366 // _this.parseExpression(scope)
371 //print("NOT PROPS"); Seed.quit();
373 //isObjectLitAr.push(false);
374 //this.braceNesting++;
376 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
379 case "PUNC.RIGHT_CURLY": // }
380 //print("<< EXIT SCOPE");
384 //print('SCOPE-WITH:' + token.toString());
385 //println("<i>"+token.data+"</i>");
386 if (this.mode == "BUILDING_SYMBOL_TREE") {
387 // Inside a 'with' block, it is impossible to figure out
388 // statically whether a symbol is a local variable or an
389 // object member. As a consequence, the only thing we can
390 // do is turn the obfuscation off for the highest scope
391 // containing the 'with' block.
392 this.protectScopeFromObfuscation(scope);
393 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
398 //print('SCOPE-CATCH:' + token.toString());
399 //println("<i>"+token.data+"</i>");
400 this.parseCatch(scope);
403 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
404 case "STRN.SINGLE_QUOTE":
405 // print('SCOPE-STRING:' + token.toString());
406 //println("<i>"+token.data+"</i>");
408 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
409 // then we are in an object lit.. -> we need to flag the brace as such...
411 isObjectLitAr.push(true);
412 //print(">>>>>> OBJLIT REPUSH(true)");
414 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
416 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
417 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
418 // see if we can replace..
419 // remove the quotes..
420 // should do a bit more checking!!!! (what about wierd char's in the string..
421 var str = token.data.substring(1,token.data.length-1);
422 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
433 //print('SCOPE-NAME:' + token.toString());
434 //print("DEAL WITH NAME:");
436 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
437 // skip anyting with "." before it..!!
439 if (this.ts.lookTok(-1).data == ".") {
440 // skip, it's an object prop.
441 //println("<i>"+token.data+"</i>");
444 //print("SYMBOL: " + token.toString());
447 if (symbol == 'this') {
450 if (this.mode == 'PASS2_SYMBOL_TREE') {
452 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
454 //print ("MUNGE?" + symbol);
456 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
458 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
459 identifier = this.getIdentifier(symbol, scope, token);
461 if (identifier == false) {
462 // BUG!find out where builtin is defined...
463 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
464 // Here, we found an undeclared and un-namespaced symbol that is
465 // 3 characters or less in length. Declare it in the global scope.
466 // We don't need to declare longer symbols since they won't cause
467 // any conflict with other munged symbols.
468 this.globalScope.declareIdentifier(symbol, token);
469 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
472 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
474 token.identifier = identifier;
475 identifier.refcount++;
480 //println("<B>SID</B>");
482 if (token.type != 'KEYW') {
485 //print('SCOPE-KEYW:' + token.toString());
486 // print("Check eval:");
490 if (this.mode == 'BUILDING_SYMBOL_TREE') {
492 if (token.name == "EVAL") {
494 //print(JSON.stringify(token, null,4));
495 // look back one and see if we can find a comment!!!
496 //if (this.ts.look(-1).type == "COMM") {
497 if (token.prefix && token.prefix.match(/eval/)) {
498 // look for eval:var:noreplace\n
501 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
502 //print("GOT: " + a);
503 var hi = _t.getIdentifier(a, scope, token);
504 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
506 // print("PROTECT "+a+" from munge");
507 //print(JSON.stringify(hi,null,4));
517 this.protectScopeFromObfuscation(scope);
518 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);
530 //print("parseScope TOK : " + token.toString());
531 token = this.ts.nextTok();
532 //if (this.ts.nextT()) break;
535 //print("<<< EXIT SCOPE");
536 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
540 parseExpression : function(scope) {
542 // Parse the expression until we encounter a comma or a semi-colon
543 // in the same brace nesting, bracket nesting and paren nesting.
544 // Parse functions if any...
545 //println("<i>EXP</i><BR/>");
546 !this.debug || print("PARSE EXPR");
549 // for printing stuff..
558 var expressionBraceNesting = this.braceNesting + 0;
559 var bracketNesting = 0;
560 var parensNesting = 0;
562 var isObjectLitAr = [ false ];
567 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
568 while ((token = this.ts.nextTok())) {
573 // moved out of loop?
574 currentScope = this.scopes[this.scopes.length-1];
576 var scopeIndent = '';
577 this.scopes.forEach(function() {
582 //this.dumpToken(token, this.scopes, this.braceNesting );
583 //print('EXPR' + token.toString());
586 //println("<i>"+token.data+"</i>");
587 //this.log("EXP:" + token.data);
588 switch (token.type) {
590 //print("EXPR-PUNC:" + token.toString());
595 //print("<< EXIT EXPRESSION");
603 case '(': //Token.LP:
604 case '{': //Token.LC:
605 case '[': //Token.LB:
606 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
607 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
608 //println("<i>"+token.data+"</i>");
612 for (var prop in token.props) {
613 if (!token.props[prop].val.length) {
614 print(JSON.stringify(token.props, null,4));
617 if (token.props[prop].val[0].data == 'function') {
618 // parse a function..
619 this.ts = new TokenStream(token.props[prop].val);
621 this.parseFunctionDeclaration(scope);
626 this.ts = new TokenStream(token.props[prop].val);
627 this.parseExpression(scope);
632 // it's an object literal..
633 // the values could be replaced..
639 token.items.forEach(function(expr) {
640 _this.ts = new TokenStream(expr);
641 _this.parseExpression(scope)
647 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
654 case ')': //Token.RP:
655 case ']': //Token.RB:
656 case '}': //Token.RB:
657 //print("<< EXIT EXPRESSION");
670 case 'STRN': // used for object lit detection..
671 //if (this.mode == 'BUILDING_SYMBOL_TREE')
672 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
680 if (this.mode == 'BUILDING_SYMBOL_TREE') {
682 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
684 //print("EXPR-NAME:" + token.toString());
687 //print("in NAME = " + token.toString());
688 //print("in NAME 0: " + this.ts.look(0).toString());
689 //print("in NAME 2: " + this.ts.lookTok(2).toString());
691 //print(this.ts.lookTok(-1).data);
693 if (this.ts.lookTok(-1).data == ".") {
697 if (symbol == 'this') {
701 if (this.mode == 'PASS2_SYMBOL_TREE') {
703 identifier = this.getIdentifier(symbol, scope, token);
704 //println("<B>??</B>");
705 if (identifier == false) {
707 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
708 // Here, we found an undeclared and un-namespaced symbol that is
709 // 3 characters or less in length. Declare it in the global scope.
710 // We don't need to declare longer symbols since they won't cause
711 // any conflict with other munged symbols.
712 this.globalScope.declareIdentifier(symbol, token);
713 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
714 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
717 //print("undeclared:" + token.toString())
722 //println("<B>++</B>");
723 token.identifier = identifier;
724 identifier.refcount++;
733 //println("<B>EID</B>");
735 //if (this.mode == 'BUILDING_SYMBOL_TREE')
736 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
738 //print('EXPR-KEYW:' + token.toString());
739 if (token.name == "FUNCTION") {
741 this.parseFunctionDeclaration(scope);
747 if (this.mode == 'BUILDING_SYMBOL_TREE') {
749 if (token.name == "EVAL") {
750 //print(JSON.stringify(token,null,4));
751 if (token.prefix && token.prefix.match(/eval:var:/g)) {
752 // look for eval:var:noreplace\n
753 // print("GOT MATCH?");
755 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
757 //print("PROTECT: " + a);
760 var hi = _t.getIdentifier(a, scope, token);
761 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
763 // println("PROTECT "+a+" from munge");
771 this.protectScopeFromObfuscation(scope);
772 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
780 //if (this.mode == 'BUILDING_SYMBOL_TREE')
781 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
786 //print("<< EXIT EXPRESSION");
791 parseCatch : function(scope) {
798 //token = getToken(-1);
799 //assert token.getType() == Token.CATCH;
800 token = this.ts.nextTok(1);
801 token = this.ts.nextTok(1);
804 //print(JSON.stringify(this.ts,null,4));
805 //assert token.getType() == Token.LP; (
806 //token = this.ts.nextTok();
807 //assert token.getType() == Token.NAME;
809 symbol = token.items[0][0].data;
812 if (this.mode == 'BUILDING_SYMBOL_TREE') {
813 // We must declare the exception identifier in the containing function
814 // scope to avoid errors related to the obfuscation process. No need to
815 // display a warning if the symbol was already declared here...
816 scope.declareIdentifier(symbol, token.items[0][0]);
818 //?? why inc the refcount?? - that should be set when building the tree???
819 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
820 identifier.refcount++;
823 //token = this.ts.nextTok();
824 //assert token.getType() == Token.RP; // )
827 parseFunctionDeclaration : function(scope)
829 //print("PARSE FUNCTION");
835 var b4braceNesting = this.braceNesting + 0;
837 //this.logR("<B>PARSING FUNCTION</B>");
840 token = this.ts.nextTok();
841 if (token.type == "NAME") {
842 if (this.mode == 'BUILDING_SYMBOL_TREE') {
843 // Get the name of the function and declare it in the current scope.
845 if (scope.getIdentifier(symbol,token) != false) {
846 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
848 scope.declareIdentifier(symbol,token);
850 token = this.ts.nextTok();
854 // return function() {....
855 while (token.data != "(") {
856 //print(token.toString());
857 token = this.ts.nextTok();
862 //assert token.getType() == Token.LP;
863 if (this.mode == 'BUILDING_SYMBOL_TREE') {
864 fnScope = new Scope(1, scope, token.n, '', token);
866 //println("STORING SCOPE" + this.ts.cursor);
868 this.indexedScopes[token.id] = fnScope;
871 //qln("FETCHING SCOPE" + this.ts.cursor);
872 fnScope = this.indexedScopes[token.id];
874 //if (this.mode == 'BUILDING_SYMBOL_TREE')
875 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
876 // Parse function arguments.
877 var args = token.items;
878 for (var argpos =0; argpos < args.length; argpos++) {
880 token = args[argpos][0];
881 //print ("FUNC ARGS: " + token.toString())
882 //assert token.getType() == Token.NAME ||
883 // token.getType() == Token.COMMA;
884 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
886 identifier = fnScope.declareIdentifier(symbol,token);
887 if (symbol == "$super" && argpos == 0) {
888 // Exception for Prototype 1.6...
889 identifier.preventMunging();
895 token = this.ts.nextTok();
896 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
898 //print(token.toString());
899 // assert token.getType() == Token.LC;
900 //this.braceNesting++;
902 //token = this.ts.nextTok();
903 //print(token.toString());
906 token.items.forEach(function(tar) {
907 _this.ts = new TokenStream(tar);
908 _this.parseScope(fnScope);
913 //print(JSON.stringify(this.ts,null,4));
914 //this.parseScope(fnScope);
916 // now pop it off the stack!!!
918 //this.braceNesting = b4braceNesting;
919 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
920 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
921 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
924 protectScopeFromObfuscation : function(scope) {
925 //assert scope != null;
927 if (scope == this.globalScope) {
928 // The global scope does not get obfuscated,
929 // so we don't need to worry about it...
933 // Find the highest local scope containing the specified scope.
934 while (scope && scope.parent != this.globalScope) {
935 scope = scope.parent;
938 //assert scope.getParentScope() == globalScope;
939 scope.preventMunging();
942 getIdentifier: function(symbol, scope, token) {
944 while (scope != false) {
945 identifier = scope.getIdentifier(symbol, token);
946 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
950 scope = scope.parent;