1 //<Script type="text/javascript">
3 Scope = imports['JSDOC/Scope.js'].Scope;
8 * // FIXME - I need this to do next() without doccomments..
11 ScopeParser = function(ts) {
15 this.indexedScopes = {};
16 this.timer = new Date() * 1;
20 // list of keywords that should not be used in object literals.
21 ScopeParser.idents = [
87 ScopeParser.prototype = {
89 timerPrint: function (str) {
90 var ntime = new Date() * 1;
91 var tdif = ntime -this.timer;
94 if (tdif > 100) { //slower ones..
97 println(pref+'['+tdif+']'+str);
101 this.warnings.push(s);
102 //println("WARNING:" + htmlescape(s) + "<BR>");
104 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
109 mode : "", //"BUILDING_SYMBOL_TREE",
111 indexedScopes : false,
118 buildSymbolTree : function()
123 this.braceNesting = 0;
129 this.globalScope = new Scope(-1, false, -1, '');
130 indexedScopes = { 0 : this.globalScope };
132 this.mode = 'BUILDING_SYMBOL_TREE';
133 this.parseScope(this.globalScope);
135 mungeSymboltree : function()
142 // One problem with obfuscation resides in the use of undeclared
143 // and un-namespaced global symbols that are 3 characters or less
144 // in length. Here is an example:
146 // var declaredGlobalVar;
148 // function declaredGlobalFn() {
150 // localvar = abc; // abc is an undeclared global symbol
153 // In the example above, there is a slim chance that localvar may be
154 // munged to 'abc', conflicting with the undeclared global symbol
155 // abc, creating a potential bug. The following code detects such
156 // global symbols. This must be done AFTER the entire file has been
157 // parsed, and BEFORE munging the symbol tree. Note that declaring
158 // extra symbols in the global scope won't hurt.
160 // Note: Since we go through all the tokens to do this, we also use
161 // the opportunity to count how many times each identifier is used.
164 this.braceNesting = 0;
166 this.mode = 'CHECKING_SYMBOL_TREE';
168 //println("MUNGING?");
170 this.parseScope(this.globalScope);
171 this.globalScope.munge();
177 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
181 //println("<B>LOG:</B>" + str + "<BR/>");
189 parseScope : function(scope) // parse a token stream..
191 //this.timerPrint("parseScope EnterScope");
197 var expressionBraceNesting = this.braceNesting;
198 var bracketNesting = 0;
199 var parensNesting = 0;
201 var isObjectLitAr = [ false ];
203 this.scopes.push(scope);
204 token = this.ts.lookT();
206 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
208 //println("START<i>"+token.data+"</i>");
211 case Script.TOKconst:
213 //this.log("parseScope GOT VAR/CONST : " + token.toString());
215 token = this.ts.nextT();
217 if (token.tokN == Script.TOKvar) { // kludge..
220 if (!token) { // can return false at EOF!
223 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
224 if (!token.isType('identifier')) {
225 println(token.toString());
226 throw "var without ident";
230 if (this.mode == "BUILDING_SYMBOL_TREE") {
231 identifier = scope.getIdentifier(token.data) ;
233 if (identifier == false) {
234 scope.declareIdentifier(token.data,token);
236 token.identifier = identifier;
237 this.warn("The variable " + symbol + " has already been declared in the same scope...");
241 token = this.ts.nextT();
243 assert token.getType() == Token.SEMI ||
244 token.getType() == Token.ASSIGN ||
245 token.getType() == Token.COMMA ||
246 token.getType() == Token.IN;
248 if (token.isType('in')) {
251 this.parseExpression();
252 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
255 if (this.ts.lookT(0).isType('semicolon')) {
261 case Script.TOKfunction:
262 //println("<i>"+token.data+"</i>");
263 this.parseFunctionDeclaration();
266 case Script.TOKlbrace: // {
267 //println("<i>"+token.data+"</i>");
268 isObjectLitAr.push(false);
272 case Script.TOKrbrace: // }
273 //println("<i>"+token.data+"</i>");
276 //assert braceNesting >= scope.getBraceNesting();
277 if (this.braceNesting == scope.braceN) {
278 var ls = this.scopes.pop();
285 //println("<i>"+token.data+"</i>");
286 if (this.mode == "BUILDING_SYMBOL_TREE") {
287 // Inside a 'with' block, it is impossible to figure out
288 // statically whether a symbol is a local variable or an
289 // object member. As a consequence, the only thing we can
290 // do is turn the obfuscation off for the highest scope
291 // containing the 'with' block.
292 this.protectScopeFromObfuscation(scope);
293 this.warn("Using 'with' is not recommended." + (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
297 case Script.TOKcatch:
298 //println("<i>"+token.data+"</i>");
302 case Token.SPECIALCOMMENT:
303 if (mode == BUILDING_SYMBOL_TREE) {
304 protectScopeFromObfuscation(scope);
305 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
310 case Script.TOKstring: // used for object lit detection..
311 //println("<i>"+token.data+"</i>");
312 if (this.ts.lookT(-1).isType('lbrace') && this.ts.lookT(1).isType('colon')) {
313 // then we are in an object lit.. -> we need to flag the brace as such...
315 isObjectLitAr.push(true);
317 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
318 if (isInObjectLitAr && this.ts.lookT(1).isType('colon') &&
319 ( this.ts.lookT(-11).isType('lbrace') || this.ts.lookT(-1).isType('comma'))) {
320 // see if we can replace..
321 // remove the quotes..
322 // should do a bit more checking!!!! (what about wierd char's in the string..
323 var str = token.data.substring(1,token.data.length-1);
324 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
338 case Script.TOKidentifier:
340 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
341 if ((this.ts.lookT(-1).tokN ==Script.TOKlbrace) && (this.ts.lookT(1).tokN == Script.TOKcolon)) {
343 isObjectLitAr.push(true);
344 //println("<i>"+token.data+"</i>");
347 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
349 if (isInObjectLitAr && (this.ts.lookT(1).tokN == Script.TOKcolon) && (this.ts.lookT(-1).tokN == Script.TOKcomma)) {
350 // skip, it's an object lit key..
351 //println("<i>"+token.data+"</i>");
356 // skip anyting with "." before it..!!
358 if (this.ts.lookT(-1).isType('dot')) {
359 // skip, it's an object prop.
360 //println("<i>"+token.data+"</i>");
364 //println("<B>SID</B>");
370 if (this.mode == 'BUILDING_SYMBOL_TREE') {
372 if (symbol == "eval") {
373 // look back one and see if we can find a comment!!!
374 if (this.ts.look(-1).isDoc()) {
375 // look for eval:var:noreplace\n
377 this.ts.look(-1).data.replace(/eval:var:([a-z_]+)/ig, function(m, a) {
379 var hi = _t.getIdentifier(a, scope);
380 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
382 // println("PROTECT "+a+" from munge");
392 this.protectScopeFromObfuscation(scope);
393 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);
398 } else if (this.mode == 'CHECKING_SYMBOL_TREE') {
400 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
404 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
406 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
407 identifier = this.getIdentifier(symbol, scope);
409 if (identifier == false) {
410 // BUG!find out where builtin is defined...
411 if (symbol.length <= 3 && JSDOC.Scope.builtin.indexOf(symbol) < 0) {
412 // Here, we found an undeclared and un-namespaced symbol that is
413 // 3 characters or less in length. Declare it in the global scope.
414 // We don't need to declare longer symbols since they won't cause
415 // any conflict with other munged symbols.
416 this.globalScope.declareIdentifier(symbol, token);
417 this.warn("Found an undeclared symbol: " + symbol, true);
420 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
422 token.identifier = identifier;
423 identifier.refcount++;
428 //case Script.TOKsemicolon':
432 //println("<i>"+token.data+"</i>");
438 //this.timerPrint("parseScope TOK : " + token.toString());
439 token = this.ts.nextT();
440 //if (this.ts.nextT()) break;
446 parseExpression : function() {
448 // Parse the expression until we encounter a comma or a semi-colon
449 // in the same brace nesting, bracket nesting and paren nesting.
450 // Parse functions if any...
451 //println("<i>EXP</i><BR/>");
457 var expressionBraceNesting = this.braceNesting;
458 var bracketNesting = 0;
459 var parensNesting = 0;
461 var isObjectLitAr = [ false ];
462 while (token = this.ts.lookT()) {
466 currentScope = this.scopes[this.scopes.length-1];
468 //println("<i>"+token.data+"</i>");
470 switch (token.type) {
474 if (this.braceNesting == expressionBraceNesting &&
475 bracketNesting == 0 &&
476 parensNesting == 0) {
482 this.parseFunctionDeclaration();
485 case 'lbrace': //Token.LC:
486 isObjectLitAr.push(false);
491 case 'rbrace': //Token.RC:
495 // assert braceNesting >= expressionBraceNesting;
498 case 'lbracket': //Token.LB:
502 case 'rbracket': //Token.RB:
506 case 'lparen': //Token.LP:
510 case 'rparen': //Token.RP:
516 case 'string': // used for object lit detection..
517 if (this.ts.lookT(-1).isType('lbrace') && this.ts.lookT(1).isType('colon')) {
518 // then we are in an object lit.. -> we need to flag the brace as such...
520 isObjectLitAr.push(true);
525 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
526 if (isInObjectLitAr && this.ts.lookT(1).isType('colon') &&
527 ( this.ts.lookT(-11).isType('lbrace') || this.ts.lookT(-1).isType('comma'))) {
528 // see if we can replace..
529 // remove the quotes..
530 var str = token.data.substring(1,token.data.length-1);
531 if (/^[a-z_]+$/i.test(str) && ScopeParser.idents.indexOf(str) < 0) {
544 case Token.SPECIALCOMMENT:
545 if (mode == BUILDING_SYMBOL_TREE) {
546 protectScopeFromObfuscation(currentScope);
547 this.warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression!" : ""), true);
553 if (this.ts.lookT(-1).isType('lbrace') && this.ts.lookT(1).isType('colon')) {
554 // then we are in an object lit.. -> we need to flag the brace as such...
556 isObjectLitAr.push(true);
559 var isInObjectLitAr = isObjectLitAr[isObjectLitAr.length-1];
560 if (isInObjectLitAr && this.ts.lookT(-1).isType('comma') && this.ts.lookT(1).isType('colon')) {
564 if (this.ts.lookT(-1).isType('dot')) {
571 //println("<B>EID</B>");
574 if (this.mode == 'BUILDING_SYMBOL_TREE') {
576 if (symbol == "eval") {
577 if (this.ts.look(-1).isDoc()) {
578 // look for eval:var:noreplace\n
580 this.ts.look(-1).data.replace(/eval:var:([a-z]+)/ig, function(m, a) {
581 var hi = _t.getIdentifier(a, currentScope);
582 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
584 // println("PROTECT "+a+" from munge");
592 this.protectScopeFromObfuscation(currentScope);
593 this.warn("Using 'eval' is not recommended." + (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
600 if (this.mode == 'CHECKING_SYMBOL_TREE') {
602 identifier = this.getIdentifier(symbol, currentScope);
603 //println("<B>??</B>");
604 if (identifier == false) {
606 if (symbol.length <= 3 && JSDOC.Scope.builtin.indexOf(symbol) < 0) {
607 // Here, we found an undeclared and un-namespaced symbol that is
608 // 3 characters or less in length. Declare it in the global scope.
609 // We don't need to declare longer symbols since they won't cause
610 // any conflict with other munged symbols.
611 this.globalScope.declareIdentifier(symbol, token);
612 this.warn("Found an undeclared symbol: " + symbol, true);
614 //println("undeclared")
619 //println("<B>++</B>");
620 token.identifier = identifier;
621 identifier.refcount++;
627 if (!this.ts.nextT()) break;
632 parseCatch : function() {
639 //token = getToken(-1);
640 //assert token.getType() == Token.CATCH;
641 token = this.ts.nextT();
642 //assert token.getType() == Token.LP; (
643 token = this.ts.nextT();
644 //assert token.getType() == Token.NAME;
647 currentScope = this.scopes[this.scopes.length-1];
649 if (this.mode == 'BUILDING_SYMBOL_TREE') {
650 // We must declare the exception identifier in the containing function
651 // scope to avoid errors related to the obfuscation process. No need to
652 // display a warning if the symbol was already declared here...
653 currentScope.declareIdentifier(symbol, token);
655 //?? why inc the refcount?? - that should be set when building the tree???
656 identifier = this.getIdentifier(symbol, currentScope);
657 identifier.refcount++;
660 token = this.ts.nextT();
661 //assert token.getType() == Token.RP; // )
664 parseFunctionDeclaration : function()
669 var currentScope = false;
672 //this.logR("<B>PARSING FUNCTION</B>");
673 currentScope = this.scopes[this.scopes.length-1];
675 token = this.ts.nextT();
676 if (token.isType('identifier')) {
677 if (this.mode == 'BUILDING_SYMBOL_TREE') {
678 // Get the name of the function and declare it in the current scope.
680 if (currentScope.getIdentifier(symbol) != false) {
681 this.warn("The function " + symbol + " has already been declared in the same scope...", true);
683 currentScope.declareIdentifier(symbol,token);
685 token = this.ts.nextT();
688 //assert token.getType() == Token.LP;
689 if (this.mode == 'BUILDING_SYMBOL_TREE') {
690 fnScope = new Scope(this.braceNesting, currentScope, token.n, '');
692 //println("STORING SCOPE" + this.ts.cursor);
694 this.indexedScopes[this.ts.cursor] = fnScope;
697 //println("FETCHING SCOPE" + this.ts.cursor);
698 fnScope = this.indexedScopes[this.ts.cursor];
701 // Parse function arguments.
703 while (!this.ts.lookT().isType('rparen')) { //(token = consumeToken()).getType() != Token.RP) {
704 token = this.ts.nextT();
706 //assert token.getType() == Token.NAME ||
707 // token.getType() == Token.COMMA;
708 if (token.isType('identifier') && this.mode == 'BUILDING_SYMBOL_TREE') {
710 identifier = fnScope.declareIdentifier(symbol,token);
711 if (symbol == "$super" && argpos == 0) {
712 // Exception for Prototype 1.6...
713 identifier.preventMunging();
719 token = this.ts.nextT();
720 // assert token.getType() == Token.LC;
723 token = this.ts.nextT();
724 if (token.isType('string') && this.ts.lookT(1).isType('semicolon')) {
727 NOT SUPPORTED YET!?!!?!
729 // This is a hint. Hints are empty statements that look like
730 // "localvar1:nomunge, localvar2:nomunge"; They allow developers
731 // to prevent specific symbols from getting obfuscated (some heretic
732 // implementations, such as Prototype 1.6, require specific variable
733 // names, such as $super for example, in order to work appropriately.
734 // Note: right now, only "nomunge" is supported in the right hand side
735 // of a hint. However, in the future, the right hand side may contain
738 String hints = token.getValue();
739 // Remove the leading and trailing quotes...
740 hints = hints.substring(1, hints.length() - 1).trim();
741 StringTokenizer st1 = new StringTokenizer(hints, ",");
742 while (st1.hasMoreTokens()) {
743 String hint = st1.nextToken();
744 int idx = hint.indexOf(':');
745 if (idx <= 0 || idx >= hint.length() - 1) {
746 if (mode == BUILDING_SYMBOL_TREE) {
747 // No need to report the error twice, hence the test...
748 this.warn("Invalid hint syntax: " + hint, true);
752 String variableName = hint.substring(0, idx).trim();
753 String variableType = hint.substring(idx + 1).trim();
754 if (mode == BUILDING_SYMBOL_TREE) {
755 fnScope.addHint(variableName, variableType);
756 } else if (mode == CHECKING_SYMBOL_TREE) {
757 identifier = fnScope.getIdentifier(variableName);
758 if (identifier != null) {
759 if (variableType.equals("nomunge")) {
760 identifier.preventMunging();
762 this.warn("Unsupported hint value: " + hint, true);
765 this.warn("Hint refers to an unknown identifier: " + hint, true);
772 this.parseScope(fnScope);
773 // now pop it off the stack!!!
779 protectScopeFromObfuscation : function(scope) {
780 //assert scope != null;
782 if (scope == this.globalScope) {
783 // The global scope does not get obfuscated,
784 // so we don't need to worry about it...
788 // Find the highest local scope containing the specified scope.
789 while (scope && scope.parent != this.globalScope) {
790 scope = scope.parent;
793 //assert scope.getParentScope() == globalScope;
794 scope.preventMunging();
797 getIdentifier: function(symbol, scope) {
799 while (scope != false) {
800 identifier = scope.getIdentifier(symbol);
801 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
805 scope = scope.parent;