6 public class ScopeParser : Object {
9 Gee.ArrayList<string> warnings;
14 public ScopeParser(TokenStream ts) {
15 this.ts = ts; // {TokenStream}
16 this.warnings = new Gee.ArrayList<string>();
18 //this.timer = new Date() * 1;
91 //print('****************' + s);
93 //println("WARNING:" + htmlescape(s) + "<BR>");
97 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
101 mode : "", //"BUILDING_SYMBOL_TREE",
103 indexedScopes : false,
110 buildSymbolTree : function()
115 this.braceNesting = 0;
117 // print(JSON.stringify(this.ts.tokens, null,4));
120 this.globalScope = new Scope(-1, false, -1, '');
121 this.indexedScopes = { 0 : this.globalScope };
123 this.mode = 'BUILDING_SYMBOL_TREE';
124 this.parseScope(this.globalScope);
126 //print("---------------END PASS 1 ---------------- ");
129 mungeSymboltree : function()
136 // One problem with obfuscation resides in the use of undeclared
137 // and un-namespaced global symbols that are 3 characters or less
138 // in length. Here is an example:
140 // var declaredGlobalVar;
142 // function declaredGlobalFn() {
144 // localvar = abc; // abc is an undeclared global symbol
147 // In the example above, there is a slim chance that localvar may be
148 // munged to 'abc', conflicting with the undeclared global symbol
149 // abc, creating a potential bug. The following code detects such
150 // global symbols. This must be done AFTER the entire file has been
151 // parsed, and BEFORE munging the symbol tree. Note that declaring
152 // extra symbols in the global scope won't hurt.
154 // Note: Since we go through all the tokens to do this, we also use
155 // the opportunity to count how many times each identifier is used.
158 this.braceNesting = 0;
159 this.mode = 'PASS2_SYMBOL_TREE';
161 //println("MUNGING?");
163 this.parseScope(this.globalScope);
165 //this.globalScope.dump();
168 this.globalScope.munge();
174 print (" ".substring(0, this.braceNesting*2) + str);
176 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
180 //println("<B>LOG:</B>" + str + "<BR/>");
187 parseScope : function(scope) // parse a token stream..
189 //this.timerPrint("parseScope EnterScope");
190 //this.log(">>> ENTER SCOPE" + this.scopes.length);
196 var expressionBraceNesting = this.braceNesting + 0;
198 var parensNesting = 0;
200 var isObjectLitAr = [ false ];
204 //var scopeIndent = '';
205 //this.scopes.forEach(function() {
206 // scopeIndent += ' ';
208 //print(">> ENTER SCOPE");
213 token = this.ts.lookTok(1);
215 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
216 //this.dumpToken(token , this.scopes, this.braceNesting);
217 //print('SCOPE:' + token.toString());
218 //this.log(token.data);
219 //if (token.type == 'NAME') {
220 // print('*' + token.data);
222 switch(token.type + '.' + token.name) {
224 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
225 //print('SCOPE-VAR:' + token.toString());
226 var vstart = this.ts.cursor +1;
228 //this.log("parseScope GOT VAR/CONST : " + token.toString());
230 token = this.ts.nextTok();
231 //!this.debug|| print( token.toString());
232 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
233 if (!token) { // can return false at EOF!
236 if (token.name == "VAR" || token.data == ',') { // kludge..
239 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
240 if (token.type != "NAME") {
241 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
242 print(this.ts.tokens[i].toString());
245 print( "var without ident");
250 if (this.mode == "BUILDING_SYMBOL_TREE") {
251 identifier = scope.getIdentifier(token.data,token) ;
253 if (identifier == false) {
254 scope.declareIdentifier(token.data, token);
256 token.identifier = identifier;
257 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
261 token = this.ts.nextTok();
262 !this.debug|| print(token.toString());
264 assert token.getType() == Token.SEMI ||
265 token.getType() == Token.ASSIGN ||
266 token.getType() == Token.COMMA ||
267 token.getType() == Token.IN;
269 if (token.name == "IN") {
272 //var bn = this.braceNesting;
273 var bn = this.braceNesting;
276 if (!token || token.type == 'VOID' || token.data == ',') {
280 token = this.ts.nextTok();
284 this.ts = new TokenStream(nts);
285 this.parseExpression(scope);
289 this.braceNesting = bn;
290 //this.braceNesting = bn;
291 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
293 token = this.ts.lookTok(1);
295 // print("AFTER EXP: " + token.toString());
296 if (token.data == ';') {
303 //this.ts.dump(vstart , this.ts.cursor);
308 case "KEYW.FUNCTION":
309 //if (this.mode == 'BUILDING_SYMBOL_TREE')
310 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
311 //println("<i>"+token.data+"</i>");
312 var bn = this.braceNesting;
313 this.parseFunctionDeclaration(scope);
314 this.braceNesting = bn;
317 case "PUNC.LEFT_CURLY": // {
318 case "PUNC.LEFT_PAREN": // (
319 case "PUNC.LEFT_BRACE": // [
320 //print('SCOPE-CURLY/PAREN:' + token.toString());
321 //println("<i>"+token.data+"</i>");
325 // { a : ... , c : .... }
327 for (var prop in token.props) {
330 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
331 if (token.props[prop].val[0].data == 'function') {
332 // parse a function..
333 this.ts = new TokenStream(token.props[prop].val);
335 this.parseFunctionDeclaration(scope);
341 this.ts = new TokenStream(token.props[prop].val);
342 this.parseExpression(scope);
347 // it's an object literal..
348 // the values could be replaced..
352 // ( ... ) or { .... } not object literals..
355 for (var xx =0; xx < token.items.length; xx++) {
356 expr = token.items[xx];
357 //token.items.forEach(function(expr) {
358 //print(expr.toString());
359 _this.ts = new TokenStream(expr);
360 //if (curTS.data == '(') {
361 _this.parseScope(scope)
363 // _this.parseExpression(scope)
368 //print("NOT PROPS"); Seed.quit();
370 //isObjectLitAr.push(false);
371 //this.braceNesting++;
373 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
376 case "PUNC.RIGHT_CURLY": // }
377 //print("<< EXIT SCOPE");
381 //print('SCOPE-WITH:' + token.toString());
382 //println("<i>"+token.data+"</i>");
383 if (this.mode == "BUILDING_SYMBOL_TREE") {
384 // Inside a 'with' block, it is impossible to figure out
385 // statically whether a symbol is a local variable or an
386 // object member. As a consequence, the only thing we can
387 // do is turn the obfuscation off for the highest scope
388 // containing the 'with' block.
389 this.protectScopeFromObfuscation(scope);
390 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
395 //print('SCOPE-CATCH:' + token.toString());
396 //println("<i>"+token.data+"</i>");
397 this.parseCatch(scope);
400 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
401 case "STRN.SINGLE_QUOTE":
402 // print('SCOPE-STRING:' + token.toString());
403 //println("<i>"+token.data+"</i>");
405 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
406 // then we are in an object lit.. -> we need to flag the brace as such...
408 isObjectLitAr.push(true);
409 //print(">>>>>> OBJLIT REPUSH(true)");
411 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
413 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
414 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
415 // see if we can replace..
416 // remove the quotes..
417 // should do a bit more checking!!!! (what about wierd char's in the string..
418 var str = token.data.substring(1,token.data.length-1);
419 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
430 //print('SCOPE-NAME:' + token.toString());
431 //print("DEAL WITH NAME:");
433 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
434 // skip anyting with "." before it..!!
436 if (this.ts.lookTok(-1).data == ".") {
437 // skip, it's an object prop.
438 //println("<i>"+token.data+"</i>");
441 //print("SYMBOL: " + token.toString());
444 if (symbol == 'this') {
447 if (this.mode == 'PASS2_SYMBOL_TREE') {
449 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
451 //print ("MUNGE?" + symbol);
453 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
455 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
456 identifier = this.getIdentifier(symbol, scope, token);
458 if (identifier == false) {
459 // BUG!find out where builtin is defined...
460 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
461 // Here, we found an undeclared and un-namespaced symbol that is
462 // 3 characters or less in length. Declare it in the global scope.
463 // We don't need to declare longer symbols since they won't cause
464 // any conflict with other munged symbols.
465 this.globalScope.declareIdentifier(symbol, token);
466 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
469 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
471 token.identifier = identifier;
472 identifier.refcount++;
477 //println("<B>SID</B>");
479 if (token.type != 'KEYW') {
482 //print('SCOPE-KEYW:' + token.toString());
483 // print("Check eval:");
487 if (this.mode == 'BUILDING_SYMBOL_TREE') {
489 if (token.name == "EVAL") {
491 //print(JSON.stringify(token, null,4));
492 // look back one and see if we can find a comment!!!
493 //if (this.ts.look(-1).type == "COMM") {
494 if (token.prefix && token.prefix.match(/eval/)) {
495 // look for eval:var:noreplace\n
498 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
499 //print("GOT: " + a);
500 var hi = _t.getIdentifier(a, scope, token);
501 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
503 // print("PROTECT "+a+" from munge");
504 //print(JSON.stringify(hi,null,4));
514 this.protectScopeFromObfuscation(scope);
515 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);
527 //print("parseScope TOK : " + token.toString());
528 token = this.ts.nextTok();
529 //if (this.ts.nextT()) break;
532 //print("<<< EXIT SCOPE");
533 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
537 parseExpression : function(scope) {
539 // Parse the expression until we encounter a comma or a semi-colon
540 // in the same brace nesting, bracket nesting and paren nesting.
541 // Parse functions if any...
542 //println("<i>EXP</i><BR/>");
543 !this.debug || print("PARSE EXPR");
546 // for printing stuff..
555 var expressionBraceNesting = this.braceNesting + 0;
556 var bracketNesting = 0;
557 var parensNesting = 0;
559 var isObjectLitAr = [ false ];
564 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
565 while ((token = this.ts.nextTok())) {
570 // moved out of loop?
571 currentScope = this.scopes[this.scopes.length-1];
573 var scopeIndent = '';
574 this.scopes.forEach(function() {
579 //this.dumpToken(token, this.scopes, this.braceNesting );
580 //print('EXPR' + token.toString());
583 //println("<i>"+token.data+"</i>");
584 //this.log("EXP:" + token.data);
585 switch (token.type) {
587 //print("EXPR-PUNC:" + token.toString());
592 //print("<< EXIT EXPRESSION");
600 case '(': //Token.LP:
601 case '{': //Token.LC:
602 case '[': //Token.LB:
603 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
604 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
605 //println("<i>"+token.data+"</i>");
609 for (var prop in token.props) {
610 if (!token.props[prop].val.length) {
611 print(JSON.stringify(token.props, null,4));
614 if (token.props[prop].val[0].data == 'function') {
615 // parse a function..
616 this.ts = new TokenStream(token.props[prop].val);
618 this.parseFunctionDeclaration(scope);
623 this.ts = new TokenStream(token.props[prop].val);
624 this.parseExpression(scope);
629 // it's an object literal..
630 // the values could be replaced..
636 token.items.forEach(function(expr) {
637 _this.ts = new TokenStream(expr);
638 _this.parseExpression(scope)
644 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
651 case ')': //Token.RP:
652 case ']': //Token.RB:
653 case '}': //Token.RB:
654 //print("<< EXIT EXPRESSION");
667 case 'STRN': // used for object lit detection..
668 //if (this.mode == 'BUILDING_SYMBOL_TREE')
669 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
677 if (this.mode == 'BUILDING_SYMBOL_TREE') {
679 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
681 //print("EXPR-NAME:" + token.toString());
684 //print("in NAME = " + token.toString());
685 //print("in NAME 0: " + this.ts.look(0).toString());
686 //print("in NAME 2: " + this.ts.lookTok(2).toString());
688 //print(this.ts.lookTok(-1).data);
690 if (this.ts.lookTok(-1).data == ".") {
694 if (symbol == 'this') {
698 if (this.mode == 'PASS2_SYMBOL_TREE') {
700 identifier = this.getIdentifier(symbol, scope, token);
701 //println("<B>??</B>");
702 if (identifier == false) {
704 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
705 // Here, we found an undeclared and un-namespaced symbol that is
706 // 3 characters or less in length. Declare it in the global scope.
707 // We don't need to declare longer symbols since they won't cause
708 // any conflict with other munged symbols.
709 this.globalScope.declareIdentifier(symbol, token);
710 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
711 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
714 //print("undeclared:" + token.toString())
719 //println("<B>++</B>");
720 token.identifier = identifier;
721 identifier.refcount++;
730 //println("<B>EID</B>");
732 //if (this.mode == 'BUILDING_SYMBOL_TREE')
733 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
735 //print('EXPR-KEYW:' + token.toString());
736 if (token.name == "FUNCTION") {
738 this.parseFunctionDeclaration(scope);
744 if (this.mode == 'BUILDING_SYMBOL_TREE') {
746 if (token.name == "EVAL") {
747 //print(JSON.stringify(token,null,4));
748 if (token.prefix && token.prefix.match(/eval:var:/g)) {
749 // look for eval:var:noreplace\n
750 // print("GOT MATCH?");
752 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
754 //print("PROTECT: " + a);
757 var hi = _t.getIdentifier(a, scope, token);
758 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
760 // println("PROTECT "+a+" from munge");
768 this.protectScopeFromObfuscation(scope);
769 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
777 //if (this.mode == 'BUILDING_SYMBOL_TREE')
778 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
783 //print("<< EXIT EXPRESSION");
788 parseCatch : function(scope) {
795 //token = getToken(-1);
796 //assert token.getType() == Token.CATCH;
797 token = this.ts.nextTok(1);
798 token = this.ts.nextTok(1);
801 //print(JSON.stringify(this.ts,null,4));
802 //assert token.getType() == Token.LP; (
803 //token = this.ts.nextTok();
804 //assert token.getType() == Token.NAME;
806 symbol = token.items[0][0].data;
809 if (this.mode == 'BUILDING_SYMBOL_TREE') {
810 // We must declare the exception identifier in the containing function
811 // scope to avoid errors related to the obfuscation process. No need to
812 // display a warning if the symbol was already declared here...
813 scope.declareIdentifier(symbol, token.items[0][0]);
815 //?? why inc the refcount?? - that should be set when building the tree???
816 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
817 identifier.refcount++;
820 //token = this.ts.nextTok();
821 //assert token.getType() == Token.RP; // )
824 parseFunctionDeclaration : function(scope)
826 //print("PARSE FUNCTION");
832 var b4braceNesting = this.braceNesting + 0;
834 //this.logR("<B>PARSING FUNCTION</B>");
837 token = this.ts.nextTok();
838 if (token.type == "NAME") {
839 if (this.mode == 'BUILDING_SYMBOL_TREE') {
840 // Get the name of the function and declare it in the current scope.
842 if (scope.getIdentifier(symbol,token) != false) {
843 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
845 scope.declareIdentifier(symbol,token);
847 token = this.ts.nextTok();
851 // return function() {....
852 while (token.data != "(") {
853 //print(token.toString());
854 token = this.ts.nextTok();
859 //assert token.getType() == Token.LP;
860 if (this.mode == 'BUILDING_SYMBOL_TREE') {
861 fnScope = new Scope(1, scope, token.n, '', token);
863 //println("STORING SCOPE" + this.ts.cursor);
865 this.indexedScopes[token.id] = fnScope;
868 //qln("FETCHING SCOPE" + this.ts.cursor);
869 fnScope = this.indexedScopes[token.id];
871 //if (this.mode == 'BUILDING_SYMBOL_TREE')
872 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
873 // Parse function arguments.
874 var args = token.items;
875 for (var argpos =0; argpos < args.length; argpos++) {
877 token = args[argpos][0];
878 //print ("FUNC ARGS: " + token.toString())
879 //assert token.getType() == Token.NAME ||
880 // token.getType() == Token.COMMA;
881 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
883 identifier = fnScope.declareIdentifier(symbol,token);
884 if (symbol == "$super" && argpos == 0) {
885 // Exception for Prototype 1.6...
886 identifier.preventMunging();
892 token = this.ts.nextTok();
893 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
895 //print(token.toString());
896 // assert token.getType() == Token.LC;
897 //this.braceNesting++;
899 //token = this.ts.nextTok();
900 //print(token.toString());
903 token.items.forEach(function(tar) {
904 _this.ts = new TokenStream(tar);
905 _this.parseScope(fnScope);
910 //print(JSON.stringify(this.ts,null,4));
911 //this.parseScope(fnScope);
913 // now pop it off the stack!!!
915 //this.braceNesting = b4braceNesting;
916 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
917 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
918 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
921 protectScopeFromObfuscation : function(scope) {
922 //assert scope != null;
924 if (scope == this.globalScope) {
925 // The global scope does not get obfuscated,
926 // so we don't need to worry about it...
930 // Find the highest local scope containing the specified scope.
931 while (scope && scope.parent != this.globalScope) {
932 scope = scope.parent;
935 //assert scope.getParentScope() == globalScope;
936 scope.preventMunging();
939 getIdentifier: function(symbol, scope, token) {
941 while (scope != false) {
942 identifier = scope.getIdentifier(symbol, token);
943 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
947 scope = scope.parent;