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.
250 var vstart = this.ts.cursor +1;
252 //this.log("parseScope GOT VAR/CONST : " + token.toString());
254 token = this.ts.nextTok();
255 !this.debug|| print( token.toString());
257 if (!token) { // can return false at EOF!
260 if (token.name == "VAR" || token.data == ',') { // kludge..
263 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
264 if (token.type !="NAME") {
265 for(var i = Math.max(this.ts.cursor-10,0); i < this.ts.cursor+1; i++) {
266 print(this.ts.tokens[i].toString());
269 print( "var without ident");
274 if (this.mode == "BUILDING_SYMBOL_TREE") {
275 identifier = scope.getIdentifier(token.data) ;
277 if (identifier == false) {
278 scope.declareIdentifier(token.data, token);
280 token.identifier = identifier;
281 this.warn("(SCOPE) The variable " + token.data + ' (line:' + token.line + ") has already been declared in the same scope...");
285 token = this.ts.nextTok();
286 !this.debug|| print(token.toString());
288 assert token.getType() == Token.SEMI ||
289 token.getType() == Token.ASSIGN ||
290 token.getType() == Token.COMMA ||
291 token.getType() == Token.IN;
293 if (token.name == "IN") {
296 //var bn = this.braceNesting;
297 var bn = this.braceNesting;
298 this.parseExpression();
299 this.braceNesting = bn;
300 //this.braceNesting = bn;
301 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
303 token = this.ts.lookTok(1);
304 !this.debug|| print("AFTER EXP: " + token.toString());
305 if (token.data == ';') {
312 //this.ts.dump(vstart , this.ts.cursor);
315 case "KEYW.FUNCTION":
316 //println("<i>"+token.data+"</i>");
317 var bn = this.braceNesting;
318 this.parseFunctionDeclaration();
319 this.braceNesting = bn;
322 case "PUNC.LEFT_CURLY": // {
323 //println("<i>"+token.data+"</i>");
324 isObjectLitAr.push(false);
327 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
330 case "PUNC.RIGHT_CURLY": // }
331 //println("<i>"+token.data+"</i>");
334 //print(">>>>>> OBJLIT POP"+ this.braceNesting);
335 //assert braceNesting >= scope.getBra ceNesting();
337 if (this.braceNesting < expressionBraceNesting) {
338 var ls = this.scopes.pop();
340 // eat symbol if we are currently at {
341 if (this.ts.look(0).data == '{') {
345 print("<<<<<<<EXIT SCOPE" +this.scopes.length);
351 //println("<i>"+token.data+"</i>");
352 if (this.mode == "BUILDING_SYMBOL_TREE") {
353 // Inside a 'with' block, it is impossible to figure out
354 // statically whether a symbol is a local variable or an
355 // object member. As a consequence, the only thing we can
356 // do is turn the obfuscation off for the highest scope
357 // containing the 'with' block.
358 this.protectScopeFromObfuscation(scope);
359 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
364 //println("<i>"+token.data+"</i>");
368 case Token.SPECIALCOMMENT:
369 if (mode == BUILDING_SYMBOL_TREE) {
370 protectScopeFromObfuscation(scope);
371 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
376 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
377 case "STRN.SINGLE_QUOTE":
378 //println("<i>"+token.data+"</i>");
379 if (this.ts.lookTok(-1).data == '{' && this.ts.lookTok(1).data == ':') {
380 // then we are in an object lit.. -> we need to flag the brace as such...
382 isObjectLitAr.push(true);
383 //print(">>>>>> OBJLIT REPUSH(true)");
385 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
387 if (isInObjectLitAr && this.ts.lookTok(1).data == ':' &&
388 ( this.ts.lookTok(-1).data == '{' || this.ts.lookTok(-1).data == ':' )) {
389 // see if we can replace..
390 // remove the quotes..
391 // should do a bit more checking!!!! (what about wierd char's in the string..
392 var str = token.data.substring(1,token.data.length-1);
393 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
407 //print("DEAL WITH NAME:");
410 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
411 if ((this.ts.lookTok(-1).data == "{") && (this.ts.lookTok(1).data == ":")) {
413 isObjectLitAr.push(true);
414 //print(">>>>>> OBJLIT REPUSH(true)");
415 //println("<i>"+token.data+"</i>");
418 // print("DEAL WITH obj lit:");
419 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
421 if (isInObjectLitAr && (this.ts.lookTok(1).data == ":") && (this.ts.lookTok(-1).data == ",")) {
422 // skip, it's an object lit key..
423 //println("<i>"+token.data+"</i>");
428 // skip anyting with "." before it..!!
430 if (this.ts.lookTok(-1).data == ".") {
431 // skip, it's an object prop.
432 //println("<i>"+token.data+"</i>");
435 //print("SYMBOL: " + token.toString());
438 if (this.mode == 'PASS2_SYMBOL_TREE') {
440 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
442 //print ("MUNGE?" + symbol);
444 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
446 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
447 identifier = this.getIdentifier(symbol, scope);
449 if (identifier == false) {
450 // BUG!find out where builtin is defined...
451 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
452 // Here, we found an undeclared and un-namespaced symbol that is
453 // 3 characters or less in length. Declare it in the global scope.
454 // We don't need to declare longer symbols since they won't cause
455 // any conflict with other munged symbols.
456 this.globalScope.declareIdentifier(symbol, token);
457 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
460 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
462 token.identifier = identifier;
463 identifier.refcount++;
468 //println("<B>SID</B>");
470 if (token.type != 'KEYW') {
473 // print("Check eval:");
477 if (this.mode == 'BUILDING_SYMBOL_TREE') {
479 if (symbol == "eval") {
480 // look back one and see if we can find a comment!!!
481 if (this.ts.look(-1).type == "COMM") {
482 // look for eval:var:noreplace\n
484 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
486 var hi = _t.getIdentifier(a, scope);
487 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
489 // println("PROTECT "+a+" from munge");
499 this.protectScopeFromObfuscation(scope);
500 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);
512 //print("parseScope TOK : " + token.toString());
513 token = this.ts.nextTok();
514 //if (this.ts.nextT()) break;
517 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
521 parseExpression : function() {
523 // Parse the expression until we encounter a comma or a semi-colon
524 // in the same brace nesting, bracket nesting and paren nesting.
525 // Parse functions if any...
526 //println("<i>EXP</i><BR/>");
527 !this.debug || print("PARSE EXPR");
530 // for printing stuff..
539 var expressionBraceNesting = this.braceNesting + 0;
540 var bracketNesting = 0;
541 var parensNesting = 0;
543 var isObjectLitAr = [ false ];
545 currentScope = this.scopes[this.scopes.length-1];
547 var scopeIndent = '';
548 this.scopes.forEach(function() {
551 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
552 while (token = this.ts.lookTok()) {
557 // moved out of loop?
558 currentScope = this.scopes[this.scopes.length-1];
560 var scopeIndent = '';
561 this.scopes.forEach(function() {
566 //this.dumpToken(token, this.scopes, this.braceNesting );
567 //print('EXP' + this.expN + ':' + token.toString());
570 //println("<i>"+token.data+"</i>");
571 //this.log("EXP:" + token.data);
572 switch (token.type) {
578 if (this.braceNesting == expressionBraceNesting &&
579 bracketNesting == 0 &&
580 parensNesting == 0) {
581 print(scopeIndent + "<< EXIT EXPRESSION");
589 case '{': //Token.LC:
590 isObjectLitAr.push(false);
593 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
596 case '}': //Token.RC:
599 //print(">>>>> EXP POP" + this.braceNesting);
600 // assert braceNesting >= expressionBraceNesting;
603 case '[': //Token.LB:
607 case ']': //Token.RB:
611 case '(': //Token.LP:
615 case ')': //Token.RP:
621 case 'STRN': // used for object lit detection..
622 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":" ) {
623 // then we are in an object lit.. -> we need to flag the brace as such...
625 isObjectLitAr.push(true);
626 //print(">>>>> EXP PUSH(true)");
631 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
632 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
633 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == "," )) {
634 // see if we can replace..
635 // remove the quotes..
636 var str = token.data.substring(1,token.data.length-1);
637 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
652 //print("in NAME = " + token.toString());
653 //print("in NAME 0: " + this.ts.look(0).toString());
654 //print("in NAME 2: " + this.ts.lookTok(2).toString());
655 if (this.ts.look(0).data == "{" && this.ts.lookTok(2).data == ":") {
656 // then we are in an object lit.. -> we need to flag the brace as such...
658 isObjectLitAr.push(true);
659 //print(">>>>> EXP PUSH(true)");
663 isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
664 //print ("isInObjectLitAr : " + isInObjectLitAr + ' ' + token.toString());
666 if (isInObjectLitAr && this.ts.lookTok(0).data == "," && this.ts.lookTok(2).data == ":") {
669 //print(this.ts.lookTok(0).data);
670 if (this.ts.lookTok(0).data == ".") {
675 if (this.mode == 'PASS2_SYMBOL_TREE') {
677 identifier = this.getIdentifier(symbol, currentScope);
678 //println("<B>??</B>");
679 if (identifier == false) {
681 if (symbol.length <= 3 && Scope.builtin.indexOf(symbol) < 0) {
682 // Here, we found an undeclared and un-namespaced symbol that is
683 // 3 characters or less in length. Declare it in the global scope.
684 // We don't need to declare longer symbols since they won't cause
685 // any conflict with other munged symbols.
686 this.globalScope.declareIdentifier(symbol, token);
687 this.warn("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')', true);
689 //println("undeclared")
694 //println("<B>++</B>");
695 token.identifier = identifier;
696 identifier.refcount++;
705 //println("<B>EID</B>");
708 if (token.name == "FUNCTION") {
710 this.parseFunctionDeclaration();
717 if (this.mode == 'BUILDING_SYMBOL_TREE') {
719 if (symbol == "eval") {
720 if (this.ts.look(-1).type == 'COMM') {
721 // look for eval:var:noreplace\n
723 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
724 var hi = _t.getIdentifier(a, currentScope);
725 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
727 // println("PROTECT "+a+" from munge");
735 this.protectScopeFromObfuscation(currentScope);
736 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
745 if (!this.ts.nextTok()) break;
747 print(scopeIndent + "<< EXIT EXPRESSION");
752 parseCatch : function() {
759 //token = getToken(-1);
760 //assert token.getType() == Token.CATCH;
761 token = this.ts.nextTok();
762 //assert token.getType() == Token.LP; (
763 token = this.ts.nextTok();
764 //assert token.getType() == Token.NAME;
767 currentScope = this.scopes[this.scopes.length-1];
769 if (this.mode == 'BUILDING_SYMBOL_TREE') {
770 // We must declare the exception identifier in the containing function
771 // scope to avoid errors related to the obfuscation process. No need to
772 // display a warning if the symbol was already declared here...
773 currentScope.declareIdentifier(symbol, token);
775 //?? why inc the refcount?? - that should be set when building the tree???
776 identifier = this.getIdentifier(symbol, currentScope);
777 identifier.refcount++;
780 token = this.ts.nextTok();
781 //assert token.getType() == Token.RP; // )
784 parseFunctionDeclaration : function()
786 //print("PARSE FUNCTION");
789 var currentScope = false;
792 var b4braceNesting = this.braceNesting + 0;
794 //this.logR("<B>PARSING FUNCTION</B>");
795 currentScope = this.scopes[this.scopes.length-1];
797 token = this.ts.nextTok();
798 if (token.type == "NAME") {
799 if (this.mode == 'BUILDING_SYMBOL_TREE') {
800 // Get the name of the function and declare it in the current scope.
802 if (currentScope.getIdentifier(symbol) != false) {
803 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
805 currentScope.declareIdentifier(symbol,token);
807 token = this.ts.nextTok();
810 //assert token.getType() == Token.LP;
811 if (this.mode == 'BUILDING_SYMBOL_TREE') {
812 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
814 //println("STORING SCOPE" + this.ts.cursor);
816 this.indexedScopes[this.ts.cursor] = fnScope;
819 //qln("FETCHING SCOPE" + this.ts.cursor);
820 fnScope = this.indexedScopes[this.ts.cursor];
824 // Parse function arguments.
826 while (this.ts.lookTok().data != ')') { //(token = consumeToken()).getType() != Token.RP) {
827 token = this.ts.nextTok();
828 // print ("FUNC ARGS: " + token.toString())
829 //assert token.getType() == Token.NAME ||
830 // token.getType() == Token.COMMA;
831 if (token.type == 'NAME' && this.mode == 'BUILDING_SYMBOL_TREE') {
833 identifier = fnScope.declareIdentifier(symbol,token);
834 if (symbol == "$super" && argpos == 0) {
835 // Exception for Prototype 1.6...
836 identifier.preventMunging();
842 token = this.ts.nextTok();
843 //print(token.toString());
844 // assert token.getType() == Token.LC;
847 token = this.ts.nextTok();
848 //print(token.toString());
851 this.parseScope(fnScope);
852 // now pop it off the stack!!!
854 this.braceNesting = b4braceNesting;
855 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
856 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
857 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
860 protectScopeFromObfuscation : function(scope) {
861 //assert scope != null;
863 if (scope == this.globalScope) {
864 // The global scope does not get obfuscated,
865 // so we don't need to worry about it...
869 // Find the highest local scope containing the specified scope.
870 while (scope && scope.parent != this.globalScope) {
871 scope = scope.parent;
874 //assert scope.getParentScope() == globalScope;
875 scope.preventMunging();
878 getIdentifier: function(symbol, scope) {
880 while (scope != false) {
881 identifier = scope.getIdentifier(symbol);
882 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
886 scope = scope.parent;