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);
208 var expressionBraceNesting = this.braceNesting + 0;
210 var parensNesting = 0;
212 var isObjectLitAr = new Gee.ArrayList<bool>();
213 isObjectLitAr.add(false);
217 //var scopeIndent = '';
218 //this.scopes.forEach(function() {
219 // scopeIndent += ' ';
221 //print(">> ENTER SCOPE");
226 var token = this.ts.lookTok(1);
227 while (token != null) {
228 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
229 //this.dumpToken(token , this.scopes, this.braceNesting);
230 //print('SCOPE:' + token.toString());
231 //this.log(token.data);
232 //if (token.type == 'NAME') {
233 // print('*' + token.data);
235 switch(token.type + '.' + token.name) {
237 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
238 //print('SCOPE-VAR:' + token.toString());
239 var vstart = this.ts.cursor +1;
241 //this.log("parseScope GOT VAR/CONST : " + token.toString());
243 token = this.ts.nextTok();
244 //!this.debug|| print( token.toString());
245 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
246 if (token == null) { // can return false at EOF!
249 if (token.name == "VAR" || token.data == ',') { // kludge..
252 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
253 if (token.type != "NAME") {
254 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
255 print(this.ts.tokens[i].toString());
258 print( "var without ident");
263 if (this.mode == "BUILDING_SYMBOL_TREE") {
264 identifier = scope.getIdentifier(token.data,token) ;
266 if (identifier == false) {
267 scope.declareIdentifier(token.data, token);
269 token.identifier = identifier;
270 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
274 token = this.ts.nextTok();
275 !this.debug|| print(token.toString());
277 assert token.getType() == Token.SEMI ||
278 token.getType() == Token.ASSIGN ||
279 token.getType() == Token.COMMA ||
280 token.getType() == Token.IN;
282 if (token.name == "IN") {
285 //var bn = this.braceNesting;
286 var bn = this.braceNesting;
289 if (!token || token.type == 'VOID' || token.data == ',') {
293 token = this.ts.nextTok();
297 this.ts = new TokenStream(nts);
298 this.parseExpression(scope);
302 this.braceNesting = bn;
303 //this.braceNesting = bn;
304 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
306 token = this.ts.lookTok(1);
308 // print("AFTER EXP: " + token.toString());
309 if (token.data == ';') {
316 //this.ts.dump(vstart , this.ts.cursor);
321 case "KEYW.FUNCTION":
322 //if (this.mode == 'BUILDING_SYMBOL_TREE')
323 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
324 //println("<i>"+token.data+"</i>");
325 var bn = this.braceNesting;
326 this.parseFunctionDeclaration(scope);
327 this.braceNesting = bn;
330 case "PUNC.LEFT_CURLY": // {
331 case "PUNC.LEFT_PAREN": // (
332 case "PUNC.LEFT_BRACE": // [
333 //print('SCOPE-CURLY/PAREN:' + token.toString());
334 //println("<i>"+token.data+"</i>");
338 // { a : ... , c : .... }
340 for (var prop in token.props) {
343 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
344 if (token.props[prop].val[0].data == 'function') {
345 // parse a function..
346 this.ts = new TokenStream(token.props[prop].val);
348 this.parseFunctionDeclaration(scope);
354 this.ts = new TokenStream(token.props[prop].val);
355 this.parseExpression(scope);
360 // it's an object literal..
361 // the values could be replaced..
365 // ( ... ) or { .... } not object literals..
368 for (var xx =0; xx < token.items.length; xx++) {
369 expr = token.items[xx];
370 //token.items.forEach(function(expr) {
371 //print(expr.toString());
372 _this.ts = new TokenStream(expr);
373 //if (curTS.data == '(') {
374 _this.parseScope(scope)
376 // _this.parseExpression(scope)
381 //print("NOT PROPS"); Seed.quit();
383 //isObjectLitAr.push(false);
384 //this.braceNesting++;
386 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
389 case "PUNC.RIGHT_CURLY": // }
390 //print("<< EXIT SCOPE");
394 //print('SCOPE-WITH:' + token.toString());
395 //println("<i>"+token.data+"</i>");
396 if (this.mode == "BUILDING_SYMBOL_TREE") {
397 // Inside a 'with' block, it is impossible to figure out
398 // statically whether a symbol is a local variable or an
399 // object member. As a consequence, the only thing we can
400 // do is turn the obfuscation off for the highest scope
401 // containing the 'with' block.
402 this.protectScopeFromObfuscation(scope);
403 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
408 //print('SCOPE-CATCH:' + token.toString());
409 //println("<i>"+token.data+"</i>");
410 this.parseCatch(scope);
413 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
414 case "STRN.SINGLE_QUOTE":
415 // print('SCOPE-STRING:' + token.toString());
416 //println("<i>"+token.data+"</i>");
418 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
419 // then we are in an object lit.. -> we need to flag the brace as such...
421 isObjectLitAr.push(true);
422 //print(">>>>>> OBJLIT REPUSH(true)");
424 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
426 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
427 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
428 // see if we can replace..
429 // remove the quotes..
430 // should do a bit more checking!!!! (what about wierd char's in the string..
431 var str = token.data.substring(1,token.data.length-1);
432 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
443 //print('SCOPE-NAME:' + token.toString());
444 //print("DEAL WITH NAME:");
446 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
447 // skip anyting with "." before it..!!
449 if (this.ts.lookTok(-1).data == ".") {
450 // skip, it's an object prop.
451 //println("<i>"+token.data+"</i>");
454 //print("SYMBOL: " + token.toString());
457 if (symbol == 'this') {
460 if (this.mode == 'PASS2_SYMBOL_TREE') {
462 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
464 //print ("MUNGE?" + symbol);
466 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
468 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
469 identifier = this.getIdentifier(symbol, scope, token);
471 if (identifier == false) {
472 // BUG!find out where builtin is defined...
473 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
474 // Here, we found an undeclared and un-namespaced symbol that is
475 // 3 characters or less in length. Declare it in the global scope.
476 // We don't need to declare longer symbols since they won't cause
477 // any conflict with other munged symbols.
478 this.globalScope.declareIdentifier(symbol, token);
479 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
482 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
484 token.identifier = identifier;
485 identifier.refcount++;
490 //println("<B>SID</B>");
492 if (token.type != 'KEYW') {
495 //print('SCOPE-KEYW:' + token.toString());
496 // print("Check eval:");
500 if (this.mode == 'BUILDING_SYMBOL_TREE') {
502 if (token.name == "EVAL") {
504 //print(JSON.stringify(token, null,4));
505 // look back one and see if we can find a comment!!!
506 //if (this.ts.look(-1).type == "COMM") {
507 if (token.prefix && token.prefix.match(/eval/)) {
508 // look for eval:var:noreplace\n
511 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
512 //print("GOT: " + a);
513 var hi = _t.getIdentifier(a, scope, token);
514 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
516 // print("PROTECT "+a+" from munge");
517 //print(JSON.stringify(hi,null,4));
527 this.protectScopeFromObfuscation(scope);
528 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);
540 //print("parseScope TOK : " + token.toString());
541 token = this.ts.nextTok();
542 //if (this.ts.nextT()) break;
545 //print("<<< EXIT SCOPE");
546 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
550 parseExpression : function(scope) {
552 // Parse the expression until we encounter a comma or a semi-colon
553 // in the same brace nesting, bracket nesting and paren nesting.
554 // Parse functions if any...
555 //println("<i>EXP</i><BR/>");
556 !this.debug || print("PARSE EXPR");
559 // for printing stuff..
568 var expressionBraceNesting = this.braceNesting + 0;
569 var bracketNesting = 0;
570 var parensNesting = 0;
572 var isObjectLitAr = [ false ];
577 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
578 while ((token = this.ts.nextTok())) {
583 // moved out of loop?
584 currentScope = this.scopes[this.scopes.length-1];
586 var scopeIndent = '';
587 this.scopes.forEach(function() {
592 //this.dumpToken(token, this.scopes, this.braceNesting );
593 //print('EXPR' + token.toString());
596 //println("<i>"+token.data+"</i>");
597 //this.log("EXP:" + token.data);
598 switch (token.type) {
600 //print("EXPR-PUNC:" + token.toString());
605 //print("<< EXIT EXPRESSION");
613 case '(': //Token.LP:
614 case '{': //Token.LC:
615 case '[': //Token.LB:
616 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
617 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
618 //println("<i>"+token.data+"</i>");
622 for (var prop in token.props) {
623 if (!token.props[prop].val.length) {
624 print(JSON.stringify(token.props, null,4));
627 if (token.props[prop].val[0].data == 'function') {
628 // parse a function..
629 this.ts = new TokenStream(token.props[prop].val);
631 this.parseFunctionDeclaration(scope);
636 this.ts = new TokenStream(token.props[prop].val);
637 this.parseExpression(scope);
642 // it's an object literal..
643 // the values could be replaced..
649 token.items.forEach(function(expr) {
650 _this.ts = new TokenStream(expr);
651 _this.parseExpression(scope)
657 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
664 case ')': //Token.RP:
665 case ']': //Token.RB:
666 case '}': //Token.RB:
667 //print("<< EXIT EXPRESSION");
680 case 'STRN': // used for object lit detection..
681 //if (this.mode == 'BUILDING_SYMBOL_TREE')
682 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
690 if (this.mode == 'BUILDING_SYMBOL_TREE') {
692 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
694 //print("EXPR-NAME:" + token.toString());
697 //print("in NAME = " + token.toString());
698 //print("in NAME 0: " + this.ts.look(0).toString());
699 //print("in NAME 2: " + this.ts.lookTok(2).toString());
701 //print(this.ts.lookTok(-1).data);
703 if (this.ts.lookTok(-1).data == ".") {
707 if (symbol == 'this') {
711 if (this.mode == 'PASS2_SYMBOL_TREE') {
713 identifier = this.getIdentifier(symbol, scope, token);
714 //println("<B>??</B>");
715 if (identifier == false) {
717 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
718 // Here, we found an undeclared and un-namespaced symbol that is
719 // 3 characters or less in length. Declare it in the global scope.
720 // We don't need to declare longer symbols since they won't cause
721 // any conflict with other munged symbols.
722 this.globalScope.declareIdentifier(symbol, token);
723 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
724 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
727 //print("undeclared:" + token.toString())
732 //println("<B>++</B>");
733 token.identifier = identifier;
734 identifier.refcount++;
743 //println("<B>EID</B>");
745 //if (this.mode == 'BUILDING_SYMBOL_TREE')
746 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
748 //print('EXPR-KEYW:' + token.toString());
749 if (token.name == "FUNCTION") {
751 this.parseFunctionDeclaration(scope);
757 if (this.mode == 'BUILDING_SYMBOL_TREE') {
759 if (token.name == "EVAL") {
760 //print(JSON.stringify(token,null,4));
761 if (token.prefix && token.prefix.match(/eval:var:/g)) {
762 // look for eval:var:noreplace\n
763 // print("GOT MATCH?");
765 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
767 //print("PROTECT: " + a);
770 var hi = _t.getIdentifier(a, scope, token);
771 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
773 // println("PROTECT "+a+" from munge");
781 this.protectScopeFromObfuscation(scope);
782 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
790 //if (this.mode == 'BUILDING_SYMBOL_TREE')
791 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
796 //print("<< EXIT EXPRESSION");
801 parseCatch : function(scope) {
808 //token = getToken(-1);
809 //assert token.getType() == Token.CATCH;
810 token = this.ts.nextTok(1);
811 token = this.ts.nextTok(1);
814 //print(JSON.stringify(this.ts,null,4));
815 //assert token.getType() == Token.LP; (
816 //token = this.ts.nextTok();
817 //assert token.getType() == Token.NAME;
819 symbol = token.items[0][0].data;
822 if (this.mode == 'BUILDING_SYMBOL_TREE') {
823 // We must declare the exception identifier in the containing function
824 // scope to avoid errors related to the obfuscation process. No need to
825 // display a warning if the symbol was already declared here...
826 scope.declareIdentifier(symbol, token.items[0][0]);
828 //?? why inc the refcount?? - that should be set when building the tree???
829 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
830 identifier.refcount++;
833 //token = this.ts.nextTok();
834 //assert token.getType() == Token.RP; // )
837 parseFunctionDeclaration : function(scope)
839 //print("PARSE FUNCTION");
845 var b4braceNesting = this.braceNesting + 0;
847 //this.logR("<B>PARSING FUNCTION</B>");
850 token = this.ts.nextTok();
851 if (token.type == "NAME") {
852 if (this.mode == 'BUILDING_SYMBOL_TREE') {
853 // Get the name of the function and declare it in the current scope.
855 if (scope.getIdentifier(symbol,token) != false) {
856 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
858 scope.declareIdentifier(symbol,token);
860 token = this.ts.nextTok();
864 // return function() {....
865 while (token.data != "(") {
866 //print(token.toString());
867 token = this.ts.nextTok();
872 //assert token.getType() == Token.LP;
873 if (this.mode == 'BUILDING_SYMBOL_TREE') {
874 fnScope = new Scope(1, scope, token.n, '', token);
876 //println("STORING SCOPE" + this.ts.cursor);
878 this.indexedScopes[token.id] = fnScope;
881 //qln("FETCHING SCOPE" + this.ts.cursor);
882 fnScope = this.indexedScopes[token.id];
884 //if (this.mode == 'BUILDING_SYMBOL_TREE')
885 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
886 // Parse function arguments.
887 var args = token.items;
888 for (var argpos =0; argpos < args.length; argpos++) {
890 token = args[argpos][0];
891 //print ("FUNC ARGS: " + token.toString())
892 //assert token.getType() == Token.NAME ||
893 // token.getType() == Token.COMMA;
894 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
896 identifier = fnScope.declareIdentifier(symbol,token);
897 if (symbol == "$super" && argpos == 0) {
898 // Exception for Prototype 1.6...
899 identifier.preventMunging();
905 token = this.ts.nextTok();
906 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
908 //print(token.toString());
909 // assert token.getType() == Token.LC;
910 //this.braceNesting++;
912 //token = this.ts.nextTok();
913 //print(token.toString());
916 token.items.forEach(function(tar) {
917 _this.ts = new TokenStream(tar);
918 _this.parseScope(fnScope);
923 //print(JSON.stringify(this.ts,null,4));
924 //this.parseScope(fnScope);
926 // now pop it off the stack!!!
928 //this.braceNesting = b4braceNesting;
929 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
930 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
931 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
934 protectScopeFromObfuscation : function(scope) {
935 //assert scope != null;
937 if (scope == this.globalScope) {
938 // The global scope does not get obfuscated,
939 // so we don't need to worry about it...
943 // Find the highest local scope containing the specified scope.
944 while (scope && scope.parent != this.globalScope) {
945 scope = scope.parent;
948 //assert scope.getParentScope() == globalScope;
949 scope.preventMunging();
952 getIdentifier: function(symbol, scope, token) {
954 while (scope != false) {
955 identifier = scope.getIdentifier(symbol, token);
956 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
960 scope = scope.parent;