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 : .... }
341 for (var prop in token.props) {
344 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
345 if (token.props[prop].val[0].data == 'function') {
346 // parse a function..
347 this.ts = new TokenStream(token.props[prop].val);
349 this.parseFunctionDeclaration(scope);
355 this.ts = new TokenStream(token.props[prop].val);
356 this.parseExpression(scope);
361 // it's an object literal..
362 // the values could be replaced..
366 // ( ... ) or { .... } not object literals..
369 for (var xx =0; xx < token.items.length; xx++) {
370 expr = token.items[xx];
371 //token.items.forEach(function(expr) {
372 //print(expr.toString());
373 _this.ts = new TokenStream(expr);
374 //if (curTS.data == '(') {
375 _this.parseScope(scope)
377 // _this.parseExpression(scope)
382 //print("NOT PROPS"); Seed.quit();
384 //isObjectLitAr.push(false);
385 //this.braceNesting++;
387 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
390 case "PUNC.RIGHT_CURLY": // }
391 //print("<< EXIT SCOPE");
395 //print('SCOPE-WITH:' + token.toString());
396 //println("<i>"+token.data+"</i>");
397 if (this.mode == "BUILDING_SYMBOL_TREE") {
398 // Inside a 'with' block, it is impossible to figure out
399 // statically whether a symbol is a local variable or an
400 // object member. As a consequence, the only thing we can
401 // do is turn the obfuscation off for the highest scope
402 // containing the 'with' block.
403 this.protectScopeFromObfuscation(scope);
404 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
409 //print('SCOPE-CATCH:' + token.toString());
410 //println("<i>"+token.data+"</i>");
411 this.parseCatch(scope);
414 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
415 case "STRN.SINGLE_QUOTE":
416 // print('SCOPE-STRING:' + token.toString());
417 //println("<i>"+token.data+"</i>");
419 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
420 // then we are in an object lit.. -> we need to flag the brace as such...
422 isObjectLitAr.push(true);
423 //print(">>>>>> OBJLIT REPUSH(true)");
425 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
427 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
428 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
429 // see if we can replace..
430 // remove the quotes..
431 // should do a bit more checking!!!! (what about wierd char's in the string..
432 var str = token.data.substring(1,token.data.length-1);
433 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
444 //print('SCOPE-NAME:' + token.toString());
445 //print("DEAL WITH NAME:");
447 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
448 // skip anyting with "." before it..!!
450 if (this.ts.lookTok(-1).data == ".") {
451 // skip, it's an object prop.
452 //println("<i>"+token.data+"</i>");
455 //print("SYMBOL: " + token.toString());
458 if (symbol == 'this') {
461 if (this.mode == 'PASS2_SYMBOL_TREE') {
463 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
465 //print ("MUNGE?" + symbol);
467 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
469 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
470 identifier = this.getIdentifier(symbol, scope, token);
472 if (identifier == false) {
473 // BUG!find out where builtin is defined...
474 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
475 // Here, we found an undeclared and un-namespaced symbol that is
476 // 3 characters or less in length. Declare it in the global scope.
477 // We don't need to declare longer symbols since they won't cause
478 // any conflict with other munged symbols.
479 this.globalScope.declareIdentifier(symbol, token);
480 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
483 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
485 token.identifier = identifier;
486 identifier.refcount++;
491 //println("<B>SID</B>");
493 if (token.type != 'KEYW') {
496 //print('SCOPE-KEYW:' + token.toString());
497 // print("Check eval:");
501 if (this.mode == 'BUILDING_SYMBOL_TREE') {
503 if (token.name == "EVAL") {
505 //print(JSON.stringify(token, null,4));
506 // look back one and see if we can find a comment!!!
507 //if (this.ts.look(-1).type == "COMM") {
508 if (token.prefix && token.prefix.match(/eval/)) {
509 // look for eval:var:noreplace\n
512 token.prefix.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
513 //print("GOT: " + a);
514 var hi = _t.getIdentifier(a, scope, token);
515 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
517 // print("PROTECT "+a+" from munge");
518 //print(JSON.stringify(hi,null,4));
528 this.protectScopeFromObfuscation(scope);
529 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);
541 //print("parseScope TOK : " + token.toString());
542 token = this.ts.nextTok();
543 //if (this.ts.nextT()) break;
546 //print("<<< EXIT SCOPE");
547 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
551 parseExpression : function(scope) {
553 // Parse the expression until we encounter a comma or a semi-colon
554 // in the same brace nesting, bracket nesting and paren nesting.
555 // Parse functions if any...
556 //println("<i>EXP</i><BR/>");
557 !this.debug || print("PARSE EXPR");
560 // for printing stuff..
569 var expressionBraceNesting = this.braceNesting + 0;
570 var bracketNesting = 0;
571 var parensNesting = 0;
573 var isObjectLitAr = [ false ];
578 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
579 while ((token = this.ts.nextTok())) {
584 // moved out of loop?
585 currentScope = this.scopes[this.scopes.length-1];
587 var scopeIndent = '';
588 this.scopes.forEach(function() {
593 //this.dumpToken(token, this.scopes, this.braceNesting );
594 //print('EXPR' + token.toString());
597 //println("<i>"+token.data+"</i>");
598 //this.log("EXP:" + token.data);
599 switch (token.type) {
601 //print("EXPR-PUNC:" + token.toString());
606 //print("<< EXIT EXPRESSION");
614 case '(': //Token.LP:
615 case '{': //Token.LC:
616 case '[': //Token.LB:
617 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
618 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
619 //println("<i>"+token.data+"</i>");
623 for (var prop in token.props) {
624 if (!token.props[prop].val.length) {
625 print(JSON.stringify(token.props, null,4));
628 if (token.props[prop].val[0].data == 'function') {
629 // parse a function..
630 this.ts = new TokenStream(token.props[prop].val);
632 this.parseFunctionDeclaration(scope);
637 this.ts = new TokenStream(token.props[prop].val);
638 this.parseExpression(scope);
643 // it's an object literal..
644 // the values could be replaced..
650 token.items.forEach(function(expr) {
651 _this.ts = new TokenStream(expr);
652 _this.parseExpression(scope)
658 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
665 case ')': //Token.RP:
666 case ']': //Token.RB:
667 case '}': //Token.RB:
668 //print("<< EXIT EXPRESSION");
681 case 'STRN': // used for object lit detection..
682 //if (this.mode == 'BUILDING_SYMBOL_TREE')
683 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
691 if (this.mode == 'BUILDING_SYMBOL_TREE') {
693 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
695 //print("EXPR-NAME:" + token.toString());
698 //print("in NAME = " + token.toString());
699 //print("in NAME 0: " + this.ts.look(0).toString());
700 //print("in NAME 2: " + this.ts.lookTok(2).toString());
702 //print(this.ts.lookTok(-1).data);
704 if (this.ts.lookTok(-1).data == ".") {
708 if (symbol == 'this') {
712 if (this.mode == 'PASS2_SYMBOL_TREE') {
714 identifier = this.getIdentifier(symbol, scope, token);
715 //println("<B>??</B>");
716 if (identifier == false) {
718 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
719 // Here, we found an undeclared and un-namespaced symbol that is
720 // 3 characters or less in length. Declare it in the global scope.
721 // We don't need to declare longer symbols since they won't cause
722 // any conflict with other munged symbols.
723 this.globalScope.declareIdentifier(symbol, token);
724 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
725 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
728 //print("undeclared:" + token.toString())
733 //println("<B>++</B>");
734 token.identifier = identifier;
735 identifier.refcount++;
744 //println("<B>EID</B>");
746 //if (this.mode == 'BUILDING_SYMBOL_TREE')
747 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
749 //print('EXPR-KEYW:' + token.toString());
750 if (token.name == "FUNCTION") {
752 this.parseFunctionDeclaration(scope);
758 if (this.mode == 'BUILDING_SYMBOL_TREE') {
760 if (token.name == "EVAL") {
761 //print(JSON.stringify(token,null,4));
762 if (token.prefix && token.prefix.match(/eval:var:/g)) {
763 // look for eval:var:noreplace\n
764 // print("GOT MATCH?");
766 token.prefix.replace(/eval:var:([a-z]+)/ig, function(m, a) {
768 //print("PROTECT: " + a);
771 var hi = _t.getIdentifier(a, scope, token);
772 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
774 // println("PROTECT "+a+" from munge");
782 this.protectScopeFromObfuscation(scope);
783 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
791 //if (this.mode == 'BUILDING_SYMBOL_TREE')
792 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
797 //print("<< EXIT EXPRESSION");
802 parseCatch : function(scope) {
809 //token = getToken(-1);
810 //assert token.getType() == Token.CATCH;
811 token = this.ts.nextTok(1);
812 token = this.ts.nextTok(1);
815 //print(JSON.stringify(this.ts,null,4));
816 //assert token.getType() == Token.LP; (
817 //token = this.ts.nextTok();
818 //assert token.getType() == Token.NAME;
820 symbol = token.items[0][0].data;
823 if (this.mode == 'BUILDING_SYMBOL_TREE') {
824 // We must declare the exception identifier in the containing function
825 // scope to avoid errors related to the obfuscation process. No need to
826 // display a warning if the symbol was already declared here...
827 scope.declareIdentifier(symbol, token.items[0][0]);
829 //?? why inc the refcount?? - that should be set when building the tree???
830 identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
831 identifier.refcount++;
834 //token = this.ts.nextTok();
835 //assert token.getType() == Token.RP; // )
838 parseFunctionDeclaration : function(scope)
840 //print("PARSE FUNCTION");
846 var b4braceNesting = this.braceNesting + 0;
848 //this.logR("<B>PARSING FUNCTION</B>");
851 token = this.ts.nextTok();
852 if (token.type == "NAME") {
853 if (this.mode == 'BUILDING_SYMBOL_TREE') {
854 // Get the name of the function and declare it in the current scope.
856 if (scope.getIdentifier(symbol,token) != false) {
857 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
859 scope.declareIdentifier(symbol,token);
861 token = this.ts.nextTok();
865 // return function() {....
866 while (token.data != "(") {
867 //print(token.toString());
868 token = this.ts.nextTok();
873 //assert token.getType() == Token.LP;
874 if (this.mode == 'BUILDING_SYMBOL_TREE') {
875 fnScope = new Scope(1, scope, token.n, '', token);
877 //println("STORING SCOPE" + this.ts.cursor);
879 this.indexedScopes[token.id] = fnScope;
882 //qln("FETCHING SCOPE" + this.ts.cursor);
883 fnScope = this.indexedScopes[token.id];
885 //if (this.mode == 'BUILDING_SYMBOL_TREE')
886 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
887 // Parse function arguments.
888 var args = token.items;
889 for (var argpos =0; argpos < args.length; argpos++) {
891 token = args[argpos][0];
892 //print ("FUNC ARGS: " + token.toString())
893 //assert token.getType() == Token.NAME ||
894 // token.getType() == Token.COMMA;
895 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
897 identifier = fnScope.declareIdentifier(symbol,token);
898 if (symbol == "$super" && argpos == 0) {
899 // Exception for Prototype 1.6...
900 identifier.preventMunging();
906 token = this.ts.nextTok();
907 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
909 //print(token.toString());
910 // assert token.getType() == Token.LC;
911 //this.braceNesting++;
913 //token = this.ts.nextTok();
914 //print(token.toString());
917 token.items.forEach(function(tar) {
918 _this.ts = new TokenStream(tar);
919 _this.parseScope(fnScope);
924 //print(JSON.stringify(this.ts,null,4));
925 //this.parseScope(fnScope);
927 // now pop it off the stack!!!
929 //this.braceNesting = b4braceNesting;
930 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
931 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
932 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
935 protectScopeFromObfuscation : function(scope) {
936 //assert scope != null;
938 if (scope == this.globalScope) {
939 // The global scope does not get obfuscated,
940 // so we don't need to worry about it...
944 // Find the highest local scope containing the specified scope.
945 while (scope && scope.parent != this.globalScope) {
946 scope = scope.parent;
949 //assert scope.getParentScope() == globalScope;
950 scope.preventMunging();
953 getIdentifier: function(symbol, scope, token) {
955 while (scope != false) {
956 identifier = scope.getIdentifier(symbol, token);
957 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
961 scope = scope.parent;