1 //<Script type="text/javascript">
3 Scope = imports['JSDOC/Scope.js'].Scope;
8 * // FIXME - I need this to do next() without doccomments..
12 * Need to make this alot simpler...
14 * so debugging is possible.
17 * at present it just runs along the stream and finds stuff then calls parseExpr .. etc,,
20 * It would be better to parse blocks of code rather than the whole stream..
28 ScopeParser = function(ts) {
29 this.ts = ts; // {TokenStream}
32 this.indexedScopes = {};
33 this.timer = new Date() * 1;
37 // list of keywords that should not be used in object literals.
38 ScopeParser.idents = [
104 ScopeParser.prototype = {
106 timerPrint: function (str) {
107 var ntime = new Date() * 1;
108 var tdif = ntime -this.timer;
111 if (tdif > 100) { //slower ones..
114 println(pref+'['+tdif+']'+str);
118 //print('****************' + s);
119 this.warnings.push(s);
120 //println("WARNING:" + htmlescape(s) + "<BR>");
122 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
127 mode : "", //"BUILDING_SYMBOL_TREE",
129 indexedScopes : false,
136 buildSymbolTree : function()
141 this.braceNesting = 0;
147 this.globalScope = new Scope(-1, false, -1, '');
148 indexedScopes = { 0 : this.globalScope };
150 this.mode = 'BUILDING_SYMBOL_TREE';
151 this.parseScope(this.globalScope);
153 //print("---------------END PASS 1 ---------------- ");
156 mungeSymboltree : function()
163 // One problem with obfuscation resides in the use of undeclared
164 // and un-namespaced global symbols that are 3 characters or less
165 // in length. Here is an example:
167 // var declaredGlobalVar;
169 // function declaredGlobalFn() {
171 // localvar = abc; // abc is an undeclared global symbol
174 // In the example above, there is a slim chance that localvar may be
175 // munged to 'abc', conflicting with the undeclared global symbol
176 // abc, creating a potential bug. The following code detects such
177 // global symbols. This must be done AFTER the entire file has been
178 // parsed, and BEFORE munging the symbol tree. Note that declaring
179 // extra symbols in the global scope won't hurt.
181 // Note: Since we go through all the tokens to do this, we also use
182 // the opportunity to count how many times each identifier is used.
185 this.braceNesting = 0;
187 this.mode = 'PASS2_SYMBOL_TREE';
189 //println("MUNGING?");
191 this.parseScope(this.globalScope);
192 this.globalScope.munge();
198 print (" ".substring(0, this.braceNesting*2) + str);
200 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
204 //println("<B>LOG:</B>" + str + "<BR/>");
211 parseScope : function(scope) // parse a token stream..
213 //this.timerPrint("parseScope EnterScope");
214 //this.log(">>> ENTER SCOPE" + this.scopes.length);
220 var expressionBraceNesting = this.braceNesting + 0;
222 var parensNesting = 0;
224 var isObjectLitAr = [ false ];
226 this.scopes.push(scope);
228 var scopeIndent = '';
229 this.scopes.forEach(function() {
232 print(scopeIndent + ">> ENTER SCOPE");
237 token = this.ts.lookTok(1);
239 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
240 //this.dumpToken(token , this.scopes, this.braceNesting);
241 //print('SCOPE:' + token.toString());
242 //this.log(token.data);
243 if (token.type == 'NAME') {
244 // print('*' + token.data);
246 switch(token.type + '.' + token.name) {
248 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
251 //this.log("parseScope GOT VAR/CONST : " + token.toString());
253 token = this.ts.nextTok();
254 !this.debug|| print( token.toString());
256 if (!token) { // can return false at EOF!
259 if (token.name == "VAR" || token.data == ',') { // kludge..
262 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
263 if (token.type !="NAME") {
264 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
265 print(this.ts.tokens[i].toString());
268 print( "var without ident");
273 if (this.mode == "BUILDING_SYMBOL_TREE") {
274 identifier = scope.getIdentifier(token.data) ;
276 if (identifier == false) {
277 scope.declareIdentifier(token.data, token);
279 token.identifier = identifier;
280 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
284 token = this.ts.nextTok();
285 !this.debug|| print(token.toString());
287 assert token.getType() == Token.SEMI ||
288 token.getType() == Token.ASSIGN ||
289 token.getType() == Token.COMMA ||
290 token.getType() == Token.IN;
292 if (token.name == "IN") {
295 //var bn = this.braceNesting;
296 var bn = this.braceNesting;
297 this.parseExpression();
298 this.braceNesting = bn;
299 //this.braceNesting = bn;
300 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
302 token = this.ts.lookTok(1);
303 !this.debug|| print("AFTER EXP: " + token.toString());
304 if (token.data == ';') {
310 case "KEYW.FUNCTION":
311 //println("<i>"+token.data+"</i>");
312 var bn = this.braceNesting;
313 this.parseFunctionDeclaration();
314 this.braceNesting = bn;
317 case "PUNC.LEFT_CURLY": // {
318 //println("<i>"+token.data+"</i>");
319 isObjectLitAr.push(false);
322 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
325 case "PUNC.RIGHT_CURLY": // }
326 //println("<i>"+token.data+"</i>");
329 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
330 //assert braceNesting >= scope.getBra ceNesting();
332 if (this.braceNesting < expressionBraceNesting) {
333 var ls = this.scopes.pop();
335 // eat symbol if we are currently at {
336 if (this.ts.look(0).data == '{') {
340 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
346 //println("<i>"+token.data+"</i>");
347 if (this.mode == "BUILDING_SYMBOL_TREE") {
348 // Inside a 'with' block, it is impossible to figure out
349 // statically whether a symbol is a local variable or an
350 // object member. As a consequence, the only thing we can
351 // do is turn the obfuscation off for the highest scope
352 // containing the 'with' block.
353 this.protectScopeFromObfuscation(scope);
354 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
359 //println("<i>"+token.data+"</i>");
363 case Token.SPECIALCOMMENT:
364 if (mode == BUILDING_SYMBOL_TREE) {
365 protectScopeFromObfuscation(scope);
366 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
371 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
372 case "STRN.SINGLE_QUOTE":
373 //println("<i>"+token.data+"</i>");
374 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
375 // then we are in an object lit.. -> we need to flag the brace as such...
377 isObjectLitAr.push(true);
378 //print(">>>>>> OBJLIT REPUSH(true)");
380 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
382 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
383 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
384 // see if we can replace..
385 // remove the quotes..
386 // should do a bit more checking!!!! (what about wierd char's in the string..
387 var str = token.data.substring(1,token.data.length-1);
388 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
402 //print("DEAL WITH NAME:");
405 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
406 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
408 isObjectLitAr.push(true);
409 //print(">>>>>> OBJLIT REPUSH(true)");
410 //println("<i>"+token.data+"</i>");
413 // print("DEAL WITH obj lit:");
414 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
416 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
417 // skip, it's an object lit key..
418 //println("<i>"+token.data+"</i>");
423 // skip anyting with "." before it..!!
425 if (this.ts.lookTok(-1).data == ".") {
426 // skip, it's an object prop.
427 //println("<i>"+token.data+"</i>");
431 if (this.mode == 'PASS2_SYMBOL_TREE') {
433 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
435 //print ("MUNGE?" + symbol);
437 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
439 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
440 identifier = this.getIdentifier(symbol, scope);
442 if (identifier == false) {
443 // BUG!find out where builtin is defined...
444 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
445 // Here, we found an undeclared and un-namespaced symbol that is
446 // 3 characters or less in length. Declare it in the global scope.
447 // We don't need to declare longer symbols since they won't cause
448 // any conflict with other munged symbols.
449 this.globalScope.declareIdentifier(symbol, token);
450 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
453 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
455 token.identifier = identifier;
456 identifier.refcount++;
461 //println("<B>SID</B>");
463 if (token.type != 'KEYW') {
466 // print("Check eval:");
470 if (this.mode == 'BUILDING_SYMBOL_TREE') {
472 if (symbol == "eval") {
473 // look back one and see if we can find a comment!!!
474 if (this.ts.look(-1).type == "COMM") {
475 // look for eval:var:noreplace\n
477 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
479 var hi = _t.getIdentifier(a, scope);
480 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
482 // println("PROTECT "+a+" from munge");
492 this.protectScopeFromObfuscation(scope);
493 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);
505 //print("parseScope TOK : " + token.toString());
506 token = this.ts.nextTok();
507 //if (this.ts.nextT()) break;
510 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
514 parseExpression : function() {
516 // Parse the expression until we encounter a comma or a semi-colon
517 // in the same brace nesting, bracket nesting and paren nesting.
518 // Parse functions if any...
519 //println("<i>EXP</i><BR/>");
520 !this.debug || print("PARSE EXPR");
523 // for printing stuff..
532 var expressionBraceNesting = this.braceNesting + 0;
533 var bracketNesting = 0;
534 var parensNesting = 0;
536 var isObjectLitAr = [ false ];
538 currentScope = this.scopes[this.scopes.length-1];
540 var scopeIndent = '';
541 this.scopes.forEach(function() {
544 print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
545 while (token = this.ts.lookTok()) {
550 // moved out of loop?
551 currentScope = this.scopes[this.scopes.length-1];
553 var scopeIndent = '';
554 this.scopes.forEach(function() {
559 //this.dumpToken(token, this.scopes, this.braceNesting );
560 print('EXP' + this.expN + ':' + token.toString());
563 //println("<i>"+token.data+"</i>");
564 //this.log("EXP:" + token.data);
565 switch (token.type) {
571 if (this.braceNesting == expressionBraceNesting &&
572 bracketNesting == 0 &&
573 parensNesting == 0) {
574 print(scopeIndent + "<< EXIT EXPRESSION");
582 case '{': //Token.LC:
583 isObjectLitAr.push(false);
586 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
589 case '}': //Token.RC:
592 //print(">>>>> EXP POP" + this.braceNesting);
593 // assert braceNesting >= expressionBraceNesting;
596 case '[': //Token.LB:
600 case ']': //Token.RB:
604 case '(': //Token.LP:
608 case ')': //Token.RP:
614 case 'STRN': // used for object lit detection..
615 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
616 // then we are in an object lit.. -> we need to flag the brace as such...
618 isObjectLitAr.push(true);
619 //print(">>>>> EXP PUSH(true)");
624 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
625 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
626 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
627 // see if we can replace..
628 // remove the quotes..
629 var str = token.data.substring(1,token.data.length-1);
630 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
645 //print("in NAME = " + token.toString());
646 //print("in NAME 0: " + this.ts.look(0).toString());
647 //print("in NAME 2: " + this.ts.lookTok(2).toString());
648 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
649 // then we are in an object lit.. -> we need to flag the brace as such...
651 isObjectLitAr.push(true);
652 //print(">>>>> EXP PUSH(true)");
656 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
657 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
659 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
662 //print(this.ts.lookTok(0).data);
663 if (this.ts.lookTok(0).data == ".") {
668 if (this.mode == 'PASS2_SYMBOL_TREE') {
670 identifier = this.getIdentifier(symbol, currentScope);
671 //println("<B>??</B>");
672 if (identifier == false) {
674 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
675 // Here, we found an undeclared and un-namespaced symbol that is
676 // 3 characters or less in length. Declare it in the global scope.
677 // We don't need to declare longer symbols since they won't cause
678 // any conflict with other munged symbols.
679 this.globalScope.declareIdentifier(symbol, token);
680 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
682 //println("undeclared")
687 //println("<B>++</B>");
688 token.identifier = identifier;
689 identifier.refcount++;
698 //println("<B>EID</B>");
701 if (token.name == "FUNCTION") {
703 this.parseFunctionDeclaration();
710 if (this.mode == 'BUILDING_SYMBOL_TREE') {
712 if (symbol == "eval") {
713 if (this.ts.look(-1).type == 'COMM') {
714 // look for eval:var:noreplace\n
716 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
717 var hi = _t.getIdentifier(a, currentScope);
718 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
720 // println("PROTECT "+a+" from munge");
728 this.protectScopeFromObfuscation(currentScope);
729 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
738 if (!this.ts.nextTok()) break;
740 print(scopeIndent + "<< EXIT EXPRESSION");
745 parseCatch : function() {
752 //token = getToken(-1);
753 //assert token.getType() == Token.CATCH;
754 token = this.ts.nextTok();
755 //assert token.getType() == Token.LP; (
756 token = this.ts.nextTok();
757 //assert token.getType() == Token.NAME;
760 currentScope = this.scopes[this.scopes.length-1];
762 if (this.mode == 'BUILDING_SYMBOL_TREE') {
763 // We must declare the exception identifier in the containing function
764 // scope to avoid errors related to the obfuscation process. No need to
765 // display a warning if the symbol was already declared here...
766 currentScope.declareIdentifier(symbol, token);
768 //?? why inc the refcount?? - that should be set when building the tree???
769 identifier = this.getIdentifier(symbol, currentScope);
770 identifier.refcount++;
773 token = this.ts.nextTok();
774 //assert token.getType() == Token.RP; // )
777 parseFunctionDeclaration : function()
779 print("PARSE FUNCTION");
782 var currentScope = false;
785 var b4braceNesting = this.braceNesting + 0;
787 //this.logR("<B>PARSING FUNCTION</B>");
788 currentScope = this.scopes[this.scopes.length-1];
790 token = this.ts.nextTok();
791 if (token.type == "NAME") {
792 if (this.mode == 'BUILDING_SYMBOL_TREE') {
793 // Get the name of the function and declare it in the current scope.
795 if (currentScope.getIdentifier(symbol) != false) {
796 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
798 currentScope.declareIdentifier(symbol,token);
800 token = this.ts.nextTok();
803 //assert token.getType() == Token.LP;
804 if (this.mode == 'BUILDING_SYMBOL_TREE') {
805 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
807 //println("STORING SCOPE" + this.ts.cursor);
809 this.indexedScopes[this.ts.cursor] = fnScope;
812 //qln("FETCHING SCOPE" + this.ts.cursor);
813 fnScope = this.indexedScopes[this.ts.cursor];
817 // Parse function arguments.
819 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
820 token = this.ts.nextTok();
821 // print ("FUNC ARGS: " + token.toString())
822 //assert token.getType() == Token.NAME ||
823 // token.getType() == Token.COMMA;
824 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
826 identifier = fnScope.declareIdentifier(symbol,token);
827 if (symbol == "$super" && argpos == 0) {
828 // Exception for Prototype 1.6...
829 identifier.preventMunging();
835 token = this.ts.nextTok();
836 print(token.toString());
837 // assert token.getType() == Token.LC;
840 token = this.ts.nextTok();
841 print(token.toString());
842 if (token.type == "STRN" && this.ts.lookTok(1).data == ';') {
845 NOT SUPPORTED YET!?!!?!
847 // This is a hint. Hints are empty statements that look like
848 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
849 // to prevent specific symbols from getting obfuscated (some heretic
850 // implementations, such as Prototype 1.6, require specific variable
851 // names, such as $super for example, in order to work appropriately.
852 // Note: right now, only "nomunge" is supported in the right hand side
853 // of a hint. However, in the future, the right hand side may contain
856 String hints = token.getValue();
857 // Remove the leading and trailing quotes...
858 hints = hints.substring(1, hints.length() - 1).trim();
859 StringTokenizer st1 = new StringTokenizer(hints, ",");
860 while (st1.hasMoreTokens()) {
861 String hint = st1.nextToken();
862 int idx = hint.indexOf(':');
863 if (idx <= 0 || idx >= hint.length() - 1) {
864 if (mode == BUILDING_SYMBOL_TREE) {
865 // No need to report the error twice, hence the test...
866 this.warn("Invalid hint syntax: " + hint, true);
870 String variableName = hint.substring(0, idx).trim();
871 String variableType = hint.substring(idx + 1).trim();
872 if (mode == BUILDING_SYMBOL_TREE) {
873 fnScope.addHint(variableName, variableType);
874 } else if (mode == CHECKING_SYMBOL_TREE) {
875 identifier = fnScope.getIdentifier(variableName);
876 if (identifier != null) {
877 if (variableType.equals("nomunge")) {
878 identifier.preventMunging();
880 this.warn("Unsupported hint value: " + hint, true);
883 this.warn("Hint refers to an unknown identifier: " + hint, true);
890 this.parseScope(fnScope);
891 // now pop it off the stack!!!
893 this.braceNesting = b4braceNesting;
894 print("ENDFN -1: " + this.ts.lookTok(-1).toString());
895 print("ENDFN 0: " + this.ts.lookTok(0).toString());
896 print("ENDFN 1: " + this.ts.lookTok(1).toString());
899 protectScopeFromObfuscation : function(scope) {
900 //assert scope != null;
902 if (scope == this.globalScope) {
903 // The global scope does not get obfuscated,
904 // so we don't need to worry about it...
908 // Find the highest local scope containing the specified scope.
909 while (scope && scope.parent != this.globalScope) {
910 scope = scope.parent;
913 //assert scope.getParentScope() == globalScope;
914 scope.preventMunging();
917 getIdentifier: function(symbol, scope) {
919 while (scope != false) {
920 identifier = scope.getIdentifier(symbol);
921 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
925 scope = scope.parent;