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") {
255 for(var i = Int.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
256 print(this.ts.tokens[i].toString());
259 print( "var without ident");
260 GLib.Process.exit (0);
264 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
265 var identifier = scope.getIdentifier(token.data,token) ;
267 if (identifier == false) {
268 scope.declareIdentifier(token.data, token);
270 token.identifier = identifier;
271 this.warn("(SCOPE) The variable " + token.data + " (line:" + token.line + ") has already been declared in the same scope...");
275 token = this.ts.nextTok();
276 //!this.debug|| print(token.toString());
278 assert token.getType() == Token.SEMI ||
279 token.getType() == Token.ASSIGN ||
280 token.getType() == Token.COMMA ||
281 token.getType() == Token.IN;
283 if (token.name == "IN") {
286 //var bn = this.braceNesting;
287 var bn = this.braceNesting;
288 var nts = new Gee.ArrayList<Token>();
290 if (!token || token.type == "VOID" || token.data == ",") {
294 token = this.ts.nextTok();
298 this.ts = new TokenStream(nts);
299 this.parseExpression(scope);
303 this.braceNesting = bn;
304 //this.braceNesting = bn;
305 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
307 token = this.ts.lookTok(1);
309 // print("AFTER EXP: " + token.toString());
310 if (token.data == ";") {
317 //this.ts.dump(vstart , this.ts.cursor);
322 case "KEYW.FUNCTION":
323 //if (this.mode == 'BUILDING_SYMBOL_TREE')
324 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
325 //println("<i>"+token.data+"</i>");
326 var bn = this.braceNesting;
327 this.parseFunctionDeclaration(scope);
328 this.braceNesting = bn;
331 case "PUNC.LEFT_CURLY": // {
332 case "PUNC.LEFT_PAREN": // (
333 case "PUNC.LEFT_BRACE": // [
334 //print('SCOPE-CURLY/PAREN:' + token.toString());
335 //println("<i>"+token.data+"</i>");
337 if (token.props.size() > 0) {
339 // { a : ... , c : .... }
340 var iter = token.props.map_iterator();
344 TokenKeyMap val = iter.get_value(); // TokenKeyMap
347 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
348 if (val.vals.get(0).data == "function") {
349 // parse a function..
350 this.ts = new TokenStream(val.vals);
352 this.parseFunctionDeclaration(scope);
358 this.ts = new TokenStream(val.vals);
359 this.parseExpression(scope);
364 // it's an object literal..
365 // the values could be replaced..
369 // ( ... ) or { .... } not object literals..
372 for (var xx =0; xx < token.items.size; xx++) {
373 expr = token.items.get(xx);
374 //token.items.forEach(function(expr) {
375 //print(expr.toString());
376 this.ts = new TokenStream(expr);
377 //if (curTS.data == '(') {
378 this.parseScope(scope);
380 // _this.parseExpression(scope)
385 //print("NOT PROPS"); Seed.quit();
387 //isObjectLitAr.push(false);
388 //this.braceNesting++;
390 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
393 case "PUNC.RIGHT_CURLY": // }
394 //print("<< EXIT SCOPE");
398 //print('SCOPE-WITH:' + token.toString());
399 //println("<i>"+token.data+"</i>");
400 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
401 // Inside a 'with' block, it is impossible to figure out
402 // statically whether a symbol is a local variable or an
403 // object member. As a consequence, the only thing we can
404 // do is turn the obfuscation off for the highest scope
405 // containing the 'with' block.
406 this.protectScopeFromObfuscation(scope);
407 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
412 //print('SCOPE-CATCH:' + token.toString());
413 //println("<i>"+token.data+"</i>");
414 this.parseCatch(scope);
417 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
418 case "STRN.SINGLE_QUOTE":
419 // print('SCOPE-STRING:' + token.toString());
420 //println("<i>"+token.data+"</i>");
422 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
423 // then we are in an object lit.. -> we need to flag the brace as such...
424 isObjectLitAr.remove_at(isObjectLitAr.size-1);
425 isObjectLitAr.add(true);
426 //print(">>>>>> OBJLIT REPUSH(true)");
428 isInObjectLitAr = isObjectLitAr.get(isObjectLitAr.size-1);
430 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
431 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == ":" )) {
432 // see if we can replace..
433 // remove the quotes..
434 // should do a bit more checking!!!! (what about wierd char's in the string..
435 var str = token.data.substring(1,token.data.length-1);
437 if (Regex.match_simple ("^[a-z_]+$", str) && this.idents.index_of(str) < 0) {
448 //print('SCOPE-NAME:' + token.toString());
449 //print("DEAL WITH NAME:");
451 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
452 // skip anyting with "." before it..!!
454 if (this.ts.lookTok(-1).data == ".") {
455 // skip, it's an object prop.
456 //println("<i>"+token.data+"</i>");
459 //print("SYMBOL: " + token.toString());
462 if (symbol == 'this') {
465 if (this.mode == 'PASS2_SYMBOL_TREE') {
467 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
469 //print ("MUNGE?" + symbol);
471 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
473 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
474 identifier = this.getIdentifier(symbol, scope, token);
476 if (identifier == false) {
477 // BUG!find out where builtin is defined...
478 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
479 // Here, we found an undeclared and un-namespaced symbol that is
480 // 3 characters or less in length. Declare it in the global scope.
481 // We don't need to declare longer symbols since they won't cause
482 // any conflict with other munged symbols.
483 this.globalScope.declareIdentifier(symbol, token);
484 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
487 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
489 token.identifier = identifier;
490 identifier.refcount++;
495 //println("<B>SID</B>");
497 if (token.type != 'KEYW') {
500 //print('SCOPE-KEYW:' + token.toString());
501 // print("Check eval:");
505 if (this.mode == 'BUILDING_SYMBOL_TREE') {
507 if (token.name == "EVAL") {
509 //print(JSON.stringify(token, null,4));
510 // look back one and see if we can find a comment!!!
511 //if (this.ts.look(-1).type == "COMM") {
512 if (token.prefix && token.prefix.match(/eval/)) {
513 // look for eval:var:noreplace\n
516 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
517 //print("GOT: " + a);
518 var hi = _t.getIdentifier(a, scope, token);
519 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
521 // print("PROTECT "+a+" from munge");
522 //print(JSON.stringify(hi,null,4));
532 this.protectScopeFromObfuscation(scope);
533 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);
545 //print("parseScope TOK : " + token.toString());
546 token = this.ts.nextTok();
547 //if (this.ts.nextT()) break;
550 //print("<<< EXIT SCOPE");
551 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
555 parseExpression : function(scope) {
557 // Parse the expression until we encounter a comma or a semi-colon
558 // in the same brace nesting, bracket nesting and paren nesting.
559 // Parse functions if any...
560 //println("<i>EXP</i><BR/>");
561 !this.debug || print("PARSE EXPR");
564 // for printing stuff..
573 var expressionBraceNesting = this.braceNesting + 0;
574 var bracketNesting = 0;
575 var parensNesting = 0;
577 var isObjectLitAr = [ false ];
582 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
583 while ((token = this.ts.nextTok())) {
588 // moved out of loop?
589 currentScope = this.scopes[this.scopes.length-1];
591 var scopeIndent = '';
592 this.scopes.forEach(function() {
597 //this.dumpToken(token, this.scopes, this.braceNesting );
598 //print('EXPR' + token.toString());
601 //println("<i>"+token.data+"</i>");
602 //this.log("EXP:" + token.data);
603 switch (token.type) {
605 //print("EXPR-PUNC:" + token.toString());
610 //print("<< EXIT EXPRESSION");
618 case '(': //Token.LP:
619 case '{': //Token.LC:
620 case '[': //Token.LB:
621 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
622 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
623 //println("<i>"+token.data+"</i>");
627 for (var prop in token.props) {
628 if (!token.props[prop].val.length) {
629 print(JSON.stringify(token.props, null,4));
632 if (token.props[prop].val[0].data == 'function') {
633 // parse a function..
634 this.ts = new TokenStream(token.props[prop].val);
636 this.parseFunctionDeclaration(scope);
641 this.ts = new TokenStream(token.props[prop].val);
642 this.parseExpression(scope);
647 // it's an object literal..
648 // the values could be replaced..
654 token.items.forEach(function(expr) {
655 _this.ts = new TokenStream(expr);
656 _this.parseExpression(scope)
662 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
669 case ')': //Token.RP:
670 case ']': //Token.RB:
671 case '}': //Token.RB:
672 //print("<< EXIT EXPRESSION");
685 case 'STRN': // used for object lit detection..
686 //if (this.mode == 'BUILDING_SYMBOL_TREE')
687 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
695 if (this.mode == 'BUILDING_SYMBOL_TREE') {
697 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
699 //print("EXPR-NAME:" + token.toString());
702 //print("in NAME = " + token.toString());
703 //print("in NAME 0: " + this.ts.look(0).toString());
704 //print("in NAME 2: " + this.ts.lookTok(2).toString());
706 //print(this.ts.lookTok(-1).data);
708 if (this.ts.lookTok(-1).data == ".") {
712 if (symbol == 'this') {
716 if (this.mode == 'PASS2_SYMBOL_TREE') {
718 identifier = this.getIdentifier(symbol, scope, token);
719 //println("<B>??</B>");
720 if (identifier == false) {
722 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
723 // Here, we found an undeclared and un-namespaced symbol that is
724 // 3 characters or less in length. Declare it in the global scope.
725 // We don't need to declare longer symbols since they won't cause
726 // any conflict with other munged symbols.
727 this.globalScope.declareIdentifier(symbol, token);
728 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
729 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
732 //print("undeclared:" + token.toString())
737 //println("<B>++</B>");
738 token.identifier = identifier;
739 identifier.refcount++;
748 //println("<B>EID</B>");
750 //if (this.mode == 'BUILDING_SYMBOL_TREE')
751 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
753 //print('EXPR-KEYW:' + token.toString());
754 if (token.name == "FUNCTION") {
756 this.parseFunctionDeclaration(scope);
762 if (this.mode == 'BUILDING_SYMBOL_TREE') {
764 if (token.name == "EVAL") {
765 //print(JSON.stringify(token,null,4));
766 if (token.prefix && token.prefix.match(/eval:var:/g)) {
767 // look for eval:var:noreplace\n
768 // print("GOT MATCH?");
770 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
772 //print("PROTECT: " + a);
775 var hi = _t.getIdentifier(a, scope, token);
776 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
778 // println("PROTECT "+a+" from munge");
786 this.protectScopeFromObfuscation(scope);
787 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
795 //if (this.mode == 'BUILDING_SYMBOL_TREE')
796 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
801 //print("<< EXIT EXPRESSION");
806 parseCatch : function(scope) {
813 //token = getToken(-1);
814 //assert token.getType() == Token.CATCH;
815 token = this.ts.nextTok(1);
816 token = this.ts.nextTok(1);
819 //print(JSON.stringify(this.ts,null,4));
820 //assert token.getType() == Token.LP; (
821 //token = this.ts.nextTok();
822 //assert token.getType() == Token.NAME;
824 symbol = token.items[0][0].data;
827 if (this.mode == 'BUILDING_SYMBOL_TREE') {
828 // We must declare the exception identifier in the containing function
829 // scope to avoid errors related to the obfuscation process. No need to
830 // display a warning if the symbol was already declared here...
831 scope.declareIdentifier(symbol, token.items[0][0]);
833 //?? why inc the refcount?? - that should be set when building the tree???
834 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
835 identifier.refcount++;
838 //token = this.ts.nextTok();
839 //assert token.getType() == Token.RP; // )
842 parseFunctionDeclaration : function(scope)
844 //print("PARSE FUNCTION");
850 var b4braceNesting = this.braceNesting + 0;
852 //this.logR("<B>PARSING FUNCTION</B>");
855 token = this.ts.nextTok();
856 if (token.type == "NAME") {
857 if (this.mode == 'BUILDING_SYMBOL_TREE') {
858 // Get the name of the function and declare it in the current scope.
860 if (scope.getIdentifier(symbol,token) != false) {
861 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
863 scope.declareIdentifier(symbol,token);
865 token = this.ts.nextTok();
869 // return function() {....
870 while (token.data != "(") {
871 //print(token.toString());
872 token = this.ts.nextTok();
877 //assert token.getType() == Token.LP;
878 if (this.mode == 'BUILDING_SYMBOL_TREE') {
879 fnScope = new Scope(1, scope, token.n, '', token);
881 //println("STORING SCOPE" + this.ts.cursor);
883 this.indexedScopes[token.id] = fnScope;
886 //qln("FETCHING SCOPE" + this.ts.cursor);
887 fnScope = this.indexedScopes[token.id];
889 //if (this.mode == 'BUILDING_SYMBOL_TREE')
890 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
891 // Parse function arguments.
892 var args = token.items;
893 for (var argpos =0; argpos < args.length; argpos++) {
895 token = args[argpos][0];
896 //print ("FUNC ARGS: " + token.toString())
897 //assert token.getType() == Token.NAME ||
898 // token.getType() == Token.COMMA;
899 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
901 identifier = fnScope.declareIdentifier(symbol,token);
902 if (symbol == "$super" && argpos == 0) {
903 // Exception for Prototype 1.6...
904 identifier.preventMunging();
910 token = this.ts.nextTok();
911 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
913 //print(token.toString());
914 // assert token.getType() == Token.LC;
915 //this.braceNesting++;
917 //token = this.ts.nextTok();
918 //print(token.toString());
921 token.items.forEach(function(tar) {
922 _this.ts = new TokenStream(tar);
923 _this.parseScope(fnScope);
928 //print(JSON.stringify(this.ts,null,4));
929 //this.parseScope(fnScope);
931 // now pop it off the stack!!!
933 //this.braceNesting = b4braceNesting;
934 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
935 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
936 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
939 protectScopeFromObfuscation : function(scope) {
940 //assert scope != null;
942 if (scope == this.globalScope) {
943 // The global scope does not get obfuscated,
944 // so we don't need to worry about it...
948 // Find the highest local scope containing the specified scope.
949 while (scope && scope.parent != this.globalScope) {
950 scope = scope.parent;
953 //assert scope.getParentScope() == globalScope;
954 scope.preventMunging();
957 getIdentifier: function(symbol, scope, token) {
959 while (scope != false) {
960 identifier = scope.getIdentifier(symbol, token);
961 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
965 scope = scope.parent;