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 = PASS2_SYMBOL_TREE;
176 //println("MUNGING?");
178 this.parseScope(this.globalScope);
180 //this.globalScope.dump();
183 this.globalScope.munge();
189 print (" ".substring(0, this.braceNesting*2) + str);
191 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
195 //println("<B>LOG:</B>" + str + "<BR/>");
202 parseScope : function(scope) // parse a token stream..
204 //this.timerPrint("parseScope EnterScope");
205 //this.log(">>> ENTER SCOPE" + this.scopes.length);
211 var expressionBraceNesting = this.braceNesting + 0;
213 var parensNesting = 0;
215 var isObjectLitAr = [ false ];
219 //var scopeIndent = '';
220 //this.scopes.forEach(function() {
221 // scopeIndent += ' ';
223 //print(">> ENTER SCOPE");
228 token = this.ts.lookTok(1);
230 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
231 //this.dumpToken(token , this.scopes, this.braceNesting);
232 //print('SCOPE:' + token.toString());
233 //this.log(token.data);
234 //if (token.type == 'NAME') {
235 // print('*' + token.data);
237 switch(token.type + '.' + token.name) {
239 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
240 //print('SCOPE-VAR:' + token.toString());
241 var vstart = this.ts.cursor +1;
243 //this.log("parseScope GOT VAR/CONST : " + token.toString());
245 token = this.ts.nextTok();
246 //!this.debug|| print( token.toString());
247 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
248 if (!token) { // can return false at EOF!
251 if (token.name == "VAR" || token.data == ',') { // kludge..
254 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
255 if (token.type != "NAME") {
256 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
257 print(this.ts.tokens[i].toString());
260 print( "var without ident");
265 if (this.mode == "BUILDING_SYMBOL_TREE") {
266 identifier = scope.getIdentifier(token.data,token) ;
268 if (identifier == false) {
269 scope.declareIdentifier(token.data, token);
271 token.identifier = identifier;
272 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
276 token = this.ts.nextTok();
277 !this.debug|| print(token.toString());
279 assert token.getType() == Token.SEMI ||
280 token.getType() == Token.ASSIGN ||
281 token.getType() == Token.COMMA ||
282 token.getType() == Token.IN;
284 if (token.name == "IN") {
287 //var bn = this.braceNesting;
288 var bn = this.braceNesting;
291 if (!token || token.type == 'VOID' || token.data == ',') {
295 token = this.ts.nextTok();
299 this.ts = new TokenStream(nts);
300 this.parseExpression(scope);
304 this.braceNesting = bn;
305 //this.braceNesting = bn;
306 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
308 token = this.ts.lookTok(1);
310 // print("AFTER EXP: " + token.toString());
311 if (token.data == ';') {
318 //this.ts.dump(vstart , this.ts.cursor);
323 case "KEYW.FUNCTION":
324 //if (this.mode == 'BUILDING_SYMBOL_TREE')
325 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
326 //println("<i>"+token.data+"</i>");
327 var bn = this.braceNesting;
328 this.parseFunctionDeclaration(scope);
329 this.braceNesting = bn;
332 case "PUNC.LEFT_CURLY": // {
333 case "PUNC.LEFT_PAREN": // (
334 case "PUNC.LEFT_BRACE": // [
335 //print('SCOPE-CURLY/PAREN:' + token.toString());
336 //println("<i>"+token.data+"</i>");
340 // { a : ... , c : .... }
342 for (var prop in token.props) {
345 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
346 if (token.props[prop].val[0].data == 'function') {
347 // parse a function..
348 this.ts = new TokenStream(token.props[prop].val);
350 this.parseFunctionDeclaration(scope);
356 this.ts = new TokenStream(token.props[prop].val);
357 this.parseExpression(scope);
362 // it's an object literal..
363 // the values could be replaced..
367 // ( ... ) or { .... } not object literals..
370 for (var xx =0; xx < token.items.length; xx++) {
371 expr = token.items[xx];
372 //token.items.forEach(function(expr) {
373 //print(expr.toString());
374 _this.ts = new TokenStream(expr);
375 //if (curTS.data == '(') {
376 _this.parseScope(scope)
378 // _this.parseExpression(scope)
383 //print("NOT PROPS"); Seed.quit();
385 //isObjectLitAr.push(false);
386 //this.braceNesting++;
388 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
391 case "PUNC.RIGHT_CURLY": // }
392 //print("<< EXIT SCOPE");
396 //print('SCOPE-WITH:' + token.toString());
397 //println("<i>"+token.data+"</i>");
398 if (this.mode == "BUILDING_SYMBOL_TREE") {
399 // Inside a 'with' block, it is impossible to figure out
400 // statically whether a symbol is a local variable or an
401 // object member. As a consequence, the only thing we can
402 // do is turn the obfuscation off for the highest scope
403 // containing the 'with' block.
404 this.protectScopeFromObfuscation(scope);
405 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
410 //print('SCOPE-CATCH:' + token.toString());
411 //println("<i>"+token.data+"</i>");
412 this.parseCatch(scope);
415 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
416 case "STRN.SINGLE_QUOTE":
417 // print('SCOPE-STRING:' + token.toString());
418 //println("<i>"+token.data+"</i>");
420 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
421 // then we are in an object lit.. -> we need to flag the brace as such...
423 isObjectLitAr.push(true);
424 //print(">>>>>> OBJLIT REPUSH(true)");
426 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
428 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
429 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
430 // see if we can replace..
431 // remove the quotes..
432 // should do a bit more checking!!!! (what about wierd char's in the string..
433 var str = token.data.substring(1,token.data.length-1);
434 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
445 //print('SCOPE-NAME:' + token.toString());
446 //print("DEAL WITH NAME:");
448 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
449 // skip anyting with "." before it..!!
451 if (this.ts.lookTok(-1).data == ".") {
452 // skip, it's an object prop.
453 //println("<i>"+token.data+"</i>");
456 //print("SYMBOL: " + token.toString());
459 if (symbol == 'this') {
462 if (this.mode == 'PASS2_SYMBOL_TREE') {
464 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
466 //print ("MUNGE?" + symbol);
468 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
470 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
471 identifier = this.getIdentifier(symbol, scope, token);
473 if (identifier == false) {
474 // BUG!find out where builtin is defined...
475 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
476 // Here, we found an undeclared and un-namespaced symbol that is
477 // 3 characters or less in length. Declare it in the global scope.
478 // We don't need to declare longer symbols since they won't cause
479 // any conflict with other munged symbols.
480 this.globalScope.declareIdentifier(symbol, token);
481 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
484 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
486 token.identifier = identifier;
487 identifier.refcount++;
492 //println("<B>SID</B>");
494 if (token.type != 'KEYW') {
497 //print('SCOPE-KEYW:' + token.toString());
498 // print("Check eval:");
502 if (this.mode == 'BUILDING_SYMBOL_TREE') {
504 if (token.name == "EVAL") {
506 //print(JSON.stringify(token, null,4));
507 // look back one and see if we can find a comment!!!
508 //if (this.ts.look(-1).type == "COMM") {
509 if (token.prefix && token.prefix.match(/eval/)) {
510 // look for eval:var:noreplace\n
513 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
514 //print("GOT: " + a);
515 var hi = _t.getIdentifier(a, scope, token);
516 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
518 // print("PROTECT "+a+" from munge");
519 //print(JSON.stringify(hi,null,4));
529 this.protectScopeFromObfuscation(scope);
530 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);
542 //print("parseScope TOK : " + token.toString());
543 token = this.ts.nextTok();
544 //if (this.ts.nextT()) break;
547 //print("<<< EXIT SCOPE");
548 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
552 parseExpression : function(scope) {
554 // Parse the expression until we encounter a comma or a semi-colon
555 // in the same brace nesting, bracket nesting and paren nesting.
556 // Parse functions if any...
557 //println("<i>EXP</i><BR/>");
558 !this.debug || print("PARSE EXPR");
561 // for printing stuff..
570 var expressionBraceNesting = this.braceNesting + 0;
571 var bracketNesting = 0;
572 var parensNesting = 0;
574 var isObjectLitAr = [ false ];
579 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
580 while ((token = this.ts.nextTok())) {
585 // moved out of loop?
586 currentScope = this.scopes[this.scopes.length-1];
588 var scopeIndent = '';
589 this.scopes.forEach(function() {
594 //this.dumpToken(token, this.scopes, this.braceNesting );
595 //print('EXPR' + token.toString());
598 //println("<i>"+token.data+"</i>");
599 //this.log("EXP:" + token.data);
600 switch (token.type) {
602 //print("EXPR-PUNC:" + token.toString());
607 //print("<< EXIT EXPRESSION");
615 case '(': //Token.LP:
616 case '{': //Token.LC:
617 case '[': //Token.LB:
618 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
619 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
620 //println("<i>"+token.data+"</i>");
624 for (var prop in token.props) {
625 if (!token.props[prop].val.length) {
626 print(JSON.stringify(token.props, null,4));
629 if (token.props[prop].val[0].data == 'function') {
630 // parse a function..
631 this.ts = new TokenStream(token.props[prop].val);
633 this.parseFunctionDeclaration(scope);
638 this.ts = new TokenStream(token.props[prop].val);
639 this.parseExpression(scope);
644 // it's an object literal..
645 // the values could be replaced..
651 token.items.forEach(function(expr) {
652 _this.ts = new TokenStream(expr);
653 _this.parseExpression(scope)
659 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
666 case ')': //Token.RP:
667 case ']': //Token.RB:
668 case '}': //Token.RB:
669 //print("<< EXIT EXPRESSION");
682 case 'STRN': // used for object lit detection..
683 //if (this.mode == 'BUILDING_SYMBOL_TREE')
684 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
692 if (this.mode == 'BUILDING_SYMBOL_TREE') {
694 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
696 //print("EXPR-NAME:" + token.toString());
699 //print("in NAME = " + token.toString());
700 //print("in NAME 0: " + this.ts.look(0).toString());
701 //print("in NAME 2: " + this.ts.lookTok(2).toString());
703 //print(this.ts.lookTok(-1).data);
705 if (this.ts.lookTok(-1).data == ".") {
709 if (symbol == 'this') {
713 if (this.mode == 'PASS2_SYMBOL_TREE') {
715 identifier = this.getIdentifier(symbol, scope, token);
716 //println("<B>??</B>");
717 if (identifier == false) {
719 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
720 // Here, we found an undeclared and un-namespaced symbol that is
721 // 3 characters or less in length. Declare it in the global scope.
722 // We don't need to declare longer symbols since they won't cause
723 // any conflict with other munged symbols.
724 this.globalScope.declareIdentifier(symbol, token);
725 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
726 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
729 //print("undeclared:" + token.toString())
734 //println("<B>++</B>");
735 token.identifier = identifier;
736 identifier.refcount++;
745 //println("<B>EID</B>");
747 //if (this.mode == 'BUILDING_SYMBOL_TREE')
748 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
750 //print('EXPR-KEYW:' + token.toString());
751 if (token.name == "FUNCTION") {
753 this.parseFunctionDeclaration(scope);
759 if (this.mode == 'BUILDING_SYMBOL_TREE') {
761 if (token.name == "EVAL") {
762 //print(JSON.stringify(token,null,4));
763 if (token.prefix && token.prefix.match(/eval:var:/g)) {
764 // look for eval:var:noreplace\n
765 // print("GOT MATCH?");
767 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
769 //print("PROTECT: " + a);
772 var hi = _t.getIdentifier(a, scope, token);
773 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
775 // println("PROTECT "+a+" from munge");
783 this.protectScopeFromObfuscation(scope);
784 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
792 //if (this.mode == 'BUILDING_SYMBOL_TREE')
793 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
798 //print("<< EXIT EXPRESSION");
803 parseCatch : function(scope) {
810 //token = getToken(-1);
811 //assert token.getType() == Token.CATCH;
812 token = this.ts.nextTok(1);
813 token = this.ts.nextTok(1);
816 //print(JSON.stringify(this.ts,null,4));
817 //assert token.getType() == Token.LP; (
818 //token = this.ts.nextTok();
819 //assert token.getType() == Token.NAME;
821 symbol = token.items[0][0].data;
824 if (this.mode == 'BUILDING_SYMBOL_TREE') {
825 // We must declare the exception identifier in the containing function
826 // scope to avoid errors related to the obfuscation process. No need to
827 // display a warning if the symbol was already declared here...
828 scope.declareIdentifier(symbol, token.items[0][0]);
830 //?? why inc the refcount?? - that should be set when building the tree???
831 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
832 identifier.refcount++;
835 //token = this.ts.nextTok();
836 //assert token.getType() == Token.RP; // )
839 parseFunctionDeclaration : function(scope)
841 //print("PARSE FUNCTION");
847 var b4braceNesting = this.braceNesting + 0;
849 //this.logR("<B>PARSING FUNCTION</B>");
852 token = this.ts.nextTok();
853 if (token.type == "NAME") {
854 if (this.mode == 'BUILDING_SYMBOL_TREE') {
855 // Get the name of the function and declare it in the current scope.
857 if (scope.getIdentifier(symbol,token) != false) {
858 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
860 scope.declareIdentifier(symbol,token);
862 token = this.ts.nextTok();
866 // return function() {....
867 while (token.data != "(") {
868 //print(token.toString());
869 token = this.ts.nextTok();
874 //assert token.getType() == Token.LP;
875 if (this.mode == 'BUILDING_SYMBOL_TREE') {
876 fnScope = new Scope(1, scope, token.n, '', token);
878 //println("STORING SCOPE" + this.ts.cursor);
880 this.indexedScopes[token.id] = fnScope;
883 //qln("FETCHING SCOPE" + this.ts.cursor);
884 fnScope = this.indexedScopes[token.id];
886 //if (this.mode == 'BUILDING_SYMBOL_TREE')
887 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
888 // Parse function arguments.
889 var args = token.items;
890 for (var argpos =0; argpos < args.length; argpos++) {
892 token = args[argpos][0];
893 //print ("FUNC ARGS: " + token.toString())
894 //assert token.getType() == Token.NAME ||
895 // token.getType() == Token.COMMA;
896 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
898 identifier = fnScope.declareIdentifier(symbol,token);
899 if (symbol == "$super" && argpos == 0) {
900 // Exception for Prototype 1.6...
901 identifier.preventMunging();
907 token = this.ts.nextTok();
908 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
910 //print(token.toString());
911 // assert token.getType() == Token.LC;
912 //this.braceNesting++;
914 //token = this.ts.nextTok();
915 //print(token.toString());
918 token.items.forEach(function(tar) {
919 _this.ts = new TokenStream(tar);
920 _this.parseScope(fnScope);
925 //print(JSON.stringify(this.ts,null,4));
926 //this.parseScope(fnScope);
928 // now pop it off the stack!!!
930 //this.braceNesting = b4braceNesting;
931 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
932 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
933 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
936 protectScopeFromObfuscation : function(scope) {
937 //assert scope != null;
939 if (scope == this.globalScope) {
940 // The global scope does not get obfuscated,
941 // so we don't need to worry about it...
945 // Find the highest local scope containing the specified scope.
946 while (scope && scope.parent != this.globalScope) {
947 scope = scope.parent;
950 //assert scope.getParentScope() == globalScope;
951 scope.preventMunging();
954 getIdentifier: function(symbol, scope, token) {
956 while (scope != false) {
957 identifier = scope.getIdentifier(symbol, token);
958 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
962 scope = scope.parent;