6 public enum ScopeParserMode {
12 public class ScopeParser : Object {
15 Gee.ArrayList<string> warnings;
18 static Gee.ArrayList<string> idents;
19 static bool initialized = false;
25 Gee.HashMap<int,Scope> indexedScopes;
34 if (ScopeParser.initialized) {
102 ScopeParser.idents = new Gee.ArrayList<string>();
103 for(var i = 0 ; i < identsar.length;i++) {
104 ScopeParser.idents.add(identsar[i]);
109 public ScopeParser(TokenStream ts) {
110 this.ts = ts; // {TokenStream}
111 this.warnings = new Gee.ArrayList<string>();
113 this.globalScope = new Scope(-1, null, -1, null);
114 this.indexedScopes = new Gee.HashMap<int,Scope>();
116 //this.indexedg = {};
117 //this.timer = new Date() * 1;
125 //print('****************' + s);
126 this.warnings.add(s);
127 //println("WARNING:" + htmlescape(s) + "<BR>");
131 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
138 public void buildSymbolTree()
143 this.braceNesting = 0;
145 // print(JSON.stringify(this.ts.tokens, null,4));
148 this.globalScope =new Scope(-1, null, -1, null);
149 this.indexedScopes = new Gee.HashMap<int,Scope>();
150 this.indexedScopes.set(0, this.globalScope );
152 this.mode = ScopeParserMode.BUILDING_SYMBOL_TREE;
154 this.parseScope(this.globalScope);
156 //print("---------------END PASS 1 ---------------- ");
160 public void mungeSymboltree()
167 // One problem with obfuscation resides in the use of undeclared
168 // and un-namespaced global symbols that are 3 characters or less
169 // in length. Here is an example:
171 // var declaredGlobalVar;
173 // function declaredGlobalFn() {
175 // localvar = abc; // abc is an undeclared global symbol
178 // In the example above, there is a slim chance that localvar may be
179 // munged to 'abc', conflicting with the undeclared global symbol
180 // abc, creating a potential bug. The following code detects such
181 // global symbols. This must be done AFTER the entire file has been
182 // parsed, and BEFORE munging the symbol tree. Note that declaring
183 // extra symbols in the global scope won't hurt.
185 // Note: Since we go through all the tokens to do this, we also use
186 // the opportunity to count how many times each identifier is used.
189 this.braceNesting = 0;
190 this.mode = ScopeParserMode.PASS2_SYMBOL_TREE;
192 //println("MUNGING?");
194 this.parseScope(this.globalScope);
196 //this.globalScope.dump();
199 this.globalScope.munge();
206 //print (" ".substring(0, this.braceNesting*2) + str);
208 //println("<B>LOG:</B>" + htmlescape(str) + "<BR/>\n");
210 void logR (string str)
212 //println("<B>LOG:</B>" + str + "<BR/>");
219 void parseScope(Scope scope) // parse a token stream..
221 //this.timerPrint("parseScope EnterScope");
222 //this.log(">>> ENTER SCOPE" + this.scopes.length);
224 var expressionBraceNesting = this.braceNesting + 0;
226 var parensNesting = 0;
228 var isObjectLitAr = new Gee.ArrayList<bool>();
229 isObjectLitAr.add(false);
233 //var scopeIndent = '';
234 //this.scopes.forEach(function() {
235 // scopeIndent += ' ';
237 //print(">> ENTER SCOPE");
242 var token = this.ts.lookTok(1);
243 while (token != null) {
244 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
245 //this.dumpToken(token , this.scopes, this.braceNesting);
246 //print('SCOPE:' + token.toString());
247 //this.log(token.data);
248 //if (token.type == 'NAME') {
249 // print('*' + token.data);
251 switch(token.type + "." + token.name) {
253 case "KEYW.CONST": // not really relivant as it's only mozzy that does this.
254 //print('SCOPE-VAR:' + token.toString());
255 var vstart = this.ts.cursor +1;
257 //this.log("parseScope GOT VAR/CONST : " + token.toString());
259 token = this.ts.nextTok();
260 //!this.debug|| print( token.toString());
261 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
262 if (token == null) { // can return false at EOF!
265 if (token.name == "VAR" || token.data == ",") { // kludge..
268 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
269 if (token.type != "NAME") {
270 this.ts.printRange( int.max(this.ts.cursor-10,0), this.ts.cursor);
272 print( "var without ident");
273 GLib.Process.exit (0);
277 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
278 var identifier = scope.getIdentifier(token.data,token) ;
280 if (identifier == null) {
281 scope.declareIdentifier(token.data, token);
283 token.identifier = identifier;
284 this.warn("(SCOPE) The variable " + token.data +
285 " (line:" + token.line.to_string() + ") has already been declared in the same scope...");
289 token = this.ts.nextTok();
290 //!this.debug|| print(token.toString());
292 assert token.getType() == Token.SEMI ||
293 token.getType() == Token.ASSIGN ||
294 token.getType() == Token.COMMA ||
295 token.getType() == Token.IN;
297 if (token.name == "IN") {
300 //var bn = this.braceNesting;
301 var bn = this.braceNesting;
302 var nts = new Gee.ArrayList<Token>();
304 if (token == null || token.type == "VOID" || token.data == ",") {
308 token = this.ts.nextTok();
312 this.ts = new TokenStream(nts);
313 this.parseExpression(scope);
317 this.braceNesting = bn;
318 //this.braceNesting = bn;
319 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
321 token = this.ts.lookTok(1);
323 // print("AFTER EXP: " + token.toString());
324 if (token.data == ";") {
331 //this.ts.dump(vstart , this.ts.cursor);
336 case "KEYW.FUNCTION":
337 //if (this.mode == 'BUILDING_SYMBOL_TREE')
338 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
339 //println("<i>"+token.data+"</i>");
340 var bn = this.braceNesting;
341 this.parseFunctionDeclaration(scope);
342 this.braceNesting = bn;
345 case "PUNC.LEFT_CURLY": // {
346 case "PUNC.LEFT_PAREN": // (
347 case "PUNC.LEFT_BRACE": // [
348 //print('SCOPE-CURLY/PAREN:' + token.toString());
349 //println("<i>"+token.data+"</i>");
351 if (token.props.size > 0) {
353 // { a : ... , c : .... }
354 var iter = token.props.map_iterator();
358 TokenKeyMap val = iter.get_value(); // TokenKeyMap
361 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
362 if (val.vals.get(0).data == "function") {
363 // parse a function..
364 this.ts = new TokenStream(val.vals);
366 this.parseFunctionDeclaration(scope);
372 this.ts = new TokenStream(val.vals);
373 this.parseExpression(scope);
378 // it's an object literal..
379 // the values could be replaced..
383 // ( ... ) or { .... } not object literals..
386 for (var xx =0; xx < token.items.size; xx++) {
387 var expr = token.items.get(xx);
388 //token.items.forEach(function(expr) {
389 //print(expr.toString());
390 this.ts = new TokenStream(expr);
391 //if (curTS.data == '(') {
392 this.parseScope(scope);
394 // _this.parseExpression(scope)
399 //print("NOT PROPS"); Seed.quit();
401 //isObjectLitAr.push(false);
402 //this.braceNesting++;
404 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
407 case "PUNC.RIGHT_CURLY": // }
408 //print("<< EXIT SCOPE");
412 //print('SCOPE-WITH:' + token.toString());
413 //println("<i>"+token.data+"</i>");
414 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
415 // Inside a 'with' block, it is impossible to figure out
416 // statically whether a symbol is a local variable or an
417 // object member. As a consequence, the only thing we can
418 // do is turn the obfuscation off for the highest scope
419 // containing the 'with' block.
420 this.protectScopeFromObfuscation(scope);
421 this.warn("Using 'with' is not recommended." +
422 (this.munge ? " Moreover, using 'with' reduces the level of compression!" : ""));
427 //print('SCOPE-CATCH:' + token.toString());
428 //println("<i>"+token.data+"</i>");
429 this.parseCatch(scope);
432 case "STRN.DOUBLE_QUOTE": // used for object lit detection..
433 case "STRN.SINGLE_QUOTE":
434 // print('SCOPE-STRING:' + token.toString());
435 //println("<i>"+token.data+"</i>");
437 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
438 // then we are in an object lit.. -> we need to flag the brace as such...
439 isObjectLitAr.remove_at(isObjectLitAr.size-1);
440 isObjectLitAr.add(true);
441 //print(">>>>>> OBJLIT REPUSH(true)");
443 var isInObjectLitAr = isObjectLitAr.get(isObjectLitAr.size-1);
445 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
446 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == ":" )) {
447 // see if we can replace..
448 // remove the quotes..
449 // should do a bit more checking!!!! (what about wierd char's in the string..
450 var str = token.data.substring(1,token.data.length-1);
452 if (Regex.match_simple ("^[a-z_]+$", str,GLib.RegexCompileFlags.CASELESS) && ScopeParser.idents.index_of(str) < 0) {
463 //print('SCOPE-NAME:' + token.toString());
464 //print("DEAL WITH NAME:");
466 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
467 // skip anyting with "." before it..!!
469 if (this.ts.lookTok(-1).data == ".") {
470 // skip, it's an object prop.
471 //println("<i>"+token.data+"</i>");
474 //print("SYMBOL: " + token.toString());
476 var symbol = token.data;
477 if (symbol == "this") {
481 if (this.mode == ScopeParserMode.PASS2_SYMBOL_TREE) {
483 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
485 //print ("MUNGE?" + symbol);
487 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
489 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
490 var identifier = this.getIdentifier(symbol, scope, token);
492 if (identifier == null) {
493 // BUG!find out where builtin is defined...
494 if (symbol.length <= 3 && Scope.builtin.index_of(symbol) < 0) {
495 // Here, we found an undeclared and un-namespaced symbol that is
496 // 3 characters or less in length. Declare it in the global scope.
497 // We don't need to declare longer symbols since they won't cause
498 // any conflict with other munged symbols.
499 this.globalScope.declareIdentifier(symbol, token);
500 this.warn("Found an undeclared symbol: " + symbol + " (line:" + token.line.to_string() + ")");
503 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
505 token.identifier = identifier;
506 identifier.refcount++;
511 //println("<B>SID</B>");
513 if (token.type != "KEYW") {
516 //print('SCOPE-KEYW:' + token.toString());
517 // print("Check eval:");
519 var symbol = token.data;
521 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
523 if (token.name == "EVAL") {
525 //print(JSON.stringify(token, null,4));
526 // look back one and see if we can find a comment!!!
527 //if (this.ts.look(-1).type == "COMM") {
528 if (token.prefix.length > 0 && Regex.match_simple ("eval",token.prefix)) {
529 // look for eval:var:noreplace\n
533 var regex = new GLib.Regex ("eval:var:([a-z_]+)",GLib.RegexCompileFlags.CASELESS );
535 regex.replace_eval (token.prefix, token.prefix.length, 0, 0, (match_info, result) => {
536 var a = match_info.fetch(0);
537 var hi = this.getIdentifier(a, scope, token);
538 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
540 // print("PROTECT "+a+" from munge");
541 //print(JSON.stringify(hi,null,4));
552 this.protectScopeFromObfuscation(scope);
553 this.warn("Using 'eval' is not recommended. (use eval:var:noreplace in comments to optimize) " +
554 (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""));
566 //print("parseScope TOK : " + token.toString());
567 token = this.ts.nextTok();
568 //if (this.ts.nextT()) break;
571 //print("<<< EXIT SCOPE");
572 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
577 void parseExpression(Scope scope)
580 // Parse the expression until we encounter a comma or a semi-colon
581 // in the same brace nesting, bracket nesting and paren nesting.
582 // Parse functions if any...
583 //println("<i>EXP</i><BR/>");
584 //!this.debug || print("PARSE EXPR");
587 // for printing stuff..
592 var expressionBraceNesting = this.braceNesting + 0;
593 var bracketNesting = 0;
594 var parensNesting = 0;
596 var isObjectLitAr = new Gee.ArrayList<bool>();
597 isObjectLitAr.add( false);
602 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
603 while (null != (token = this.ts.nextTok())) {
608 // moved out of loop?
609 currentScope = this.scopes[this.scopes.length-1];
611 var scopeIndent = '';
612 this.scopes.forEach(function() {
617 //this.dumpToken(token, this.scopes, this.braceNesting );
618 //print('EXPR' + token.toString());
621 //println("<i>"+token.data+"</i>");
622 //this.log("EXP:" + token.data);
623 switch (token.type) {
625 //print("EXPR-PUNC:" + token.toString());
630 //print("<< EXIT EXPRESSION");
638 case "(": //Token.LP:
639 case "{": //Token.LC:
640 case "[": //Token.LB:
641 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
642 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
643 //println("<i>"+token.data+"</i>");
645 if (token.props.size > 0) {
647 var iter = token.props.map_iterator();
651 TokenKeyMap val = iter.get_value(); // TokenKeyMap
655 //if (val.vals.size < 1) {
656 //print(JSON.stringify(token.props, null,4));
659 if (val.vals.get(0).data == "function") {
660 // parse a function..
661 this.ts = new TokenStream(val.vals);
663 this.parseFunctionDeclaration(scope);
668 this.ts = new TokenStream(val.vals);
669 this.parseExpression(scope);
674 // it's an object literal..
675 // the values could be replaced..
681 foreach(var expr in token.items) {
683 this.ts = new TokenStream(expr);
684 this.parseExpression(scope);
690 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
697 case ")": //Token.RP:
698 case "]": //Token.RB:
699 case "}": //Token.RB:
700 //print("<< EXIT EXPRESSION");
713 case "STRN": // used for object lit detection..
714 //if (this.mode == 'BUILDING_SYMBOL_TREE')
715 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
723 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
725 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
727 //print("EXPR-NAME:" + token.toString());
729 var symbol = token.data;
730 //print("in NAME = " + token.toString());
731 //print("in NAME 0: " + this.ts.look(0).toString());
732 //print("in NAME 2: " + this.ts.lookTok(2).toString());
734 //print(this.ts.lookTok(-1).data);
736 if (this.ts.lookTok(-1).data == ".") {
740 if (symbol == "this") {
744 if (this.mode == ScopeParserMode.PASS2_SYMBOL_TREE) {
746 var identifier = this.getIdentifier(symbol, scope, token);
747 //println("<B>??</B>");
748 if (identifier == null) {
750 if (symbol.length <= 3 && Scope.builtin.index_of(symbol) < 0) {
751 // Here, we found an undeclared and un-namespaced symbol that is
752 // 3 characters or less in length. Declare it in the global scope.
753 // We don't need to declare longer symbols since they won't cause
754 // any conflict with other munged symbols.
755 this.globalScope.declareIdentifier(symbol, token);
756 this.warn("Found an undeclared symbol: " + symbol + " (line:" + token.line.to_string() + ")");
757 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
760 //print("undeclared:" + token.toString())
765 //println("<B>++</B>");
766 token.identifier = identifier;
767 identifier.refcount++;
776 //println("<B>EID</B>");
778 //if (this.mode == 'BUILDING_SYMBOL_TREE')
779 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
781 //print('EXPR-KEYW:' + token.toString());
782 if (token.name == "FUNCTION") {
784 this.parseFunctionDeclaration(scope);
789 var symbol = token.data;
790 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
792 if (token.name == "EVAL") {
795 //print(JSON.stringify(token,null,4));
797 if (token.prefix.length > 0 && Regex.match_simple ("eval:var:", token.prefix,GLib.RegexCompileFlags.CASELESS)) {
798 // look for eval:var:noreplace\n
799 // print("GOT MATCH?");
802 var regex = new GLib.Regex ("eval:var:([a-z_]+)",GLib.RegexCompileFlags.CASELESS );
804 regex.replace_eval (token.prefix, token.prefix.length, 0, 0, (match_info, result) => {
805 var a = match_info.fetch(0);
806 //print("PROTECT: " + a);
809 var hi = this.getIdentifier(a, scope, token);
810 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
812 // println("PROTECT "+a+" from munge");
820 this.protectScopeFromObfuscation(scope);
821 this.warn("Using 'eval' is not recommended." +
822 (this.munge ? " Moreover, using 'eval' reduces the level of compression!" : ""));
831 //if (this.mode == 'BUILDING_SYMBOL_TREE')
832 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
837 //print("<< EXIT EXPRESSION");
842 void parseCatch(Scope scope) {
845 //token = getToken(-1);
846 //assert token.getType() == Token.CATCH;
847 var token = this.ts.nextTok();
848 token = this.ts.nextTok();
851 //print(JSON.stringify(this.ts,null,4));
852 //assert token.getType() == Token.LP; (
853 //token = this.ts.nextTok();
854 //assert token.getType() == Token.NAME;
856 var symbol = token.items[0][0].data;
859 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
860 // We must declare the exception identifier in the containing function
861 // scope to avoid errors related to the obfuscation process. No need to
862 // display a warning if the symbol was already declared here...
863 scope.declareIdentifier(symbol, token.items[0][0]);
865 //?? why inc the refcount?? - that should be set when building the tree???
866 var identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
867 identifier.refcount++;
870 //token = this.ts.nextTok();
871 //assert token.getType() == Token.RP; // )
874 void parseFunctionDeclaration (Scope scope)
876 //print("PARSE FUNCTION");
879 var b4braceNesting = this.braceNesting + 0;
881 //this.logR("<B>PARSING FUNCTION</B>");
884 var token = this.ts.nextTok();
885 if (token.type == "NAME") {
886 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
887 // Get the name of the function and declare it in the current scope.
888 var symbol = token.data;
889 if (scope.getIdentifier(symbol,token) != null) {
890 this.warn("The function " + symbol + " has already been declared in the same scope...");
892 scope.declareIdentifier(symbol,token);
894 token = this.ts.nextTok();
898 // return function() {....
899 while (token.data != "(") {
900 //print(token.toString());
901 token = this.ts.nextTok();
906 //assert token.getType() == Token.LP;
907 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
908 fnScope = new Scope(1, scope, token.id, token);
910 //println("STORING SCOPE" + this.ts.cursor);
912 this.indexedScopes.set(token.id,fnScope);
915 //qln("FETCHING SCOPE" + this.ts.cursor);
916 fnScope = this.indexedScopes[token.id];
918 //if (this.mode == 'BUILDING_SYMBOL_TREE')
919 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
920 // Parse function arguments.
921 var args = token.items;
922 for (var argpos =0; argpos < args.size; argpos++) {
924 token = args.get(argpos).get(0);
925 //print ("FUNC ARGS: " + token.toString())
926 //assert token.getType() == Token.NAME ||
927 // token.getType() == Token.COMMA;
928 if (token.type == "NAME" && this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
929 var symbol = token.data;
930 var identifier = fnScope.declareIdentifier(symbol,token);
931 if (symbol == "$super" && argpos == 0) {
932 // Exception for Prototype 1.6...
933 identifier.toMunge = false;
939 token = this.ts.nextTok();
940 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
942 //print(token.toString());
943 // assert token.getType() == Token.LC;
944 //this.braceNesting++;
946 //token = this.ts.nextTok();
947 //print(token.toString());
949 foreach(var tar in token.items) {
950 this.ts = new TokenStream(tar);
951 this.parseScope(fnScope);
955 //print(JSON.stringify(this.ts,null,4));
956 //this.parseScope(fnScope);
958 // now pop it off the stack!!!
960 //this.braceNesting = b4braceNesting;
961 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
962 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
963 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
966 void protectScopeFromObfuscation (Scope scope) {
967 //assert scope != null;
969 if (scope == this.globalScope) {
970 // The global scope does not get obfuscated,
971 // so we don't need to worry about it...
975 // Find the highest local scope containing the specified scope.
976 while (scope != null && scope.parent != this.globalScope) {
977 scope = scope.parent;
980 //assert scope.getParentScope() == globalScope;
981 scope.preventMunging();
984 Identifier? getIdentifier(string symbol, Scope in_scope, Token token)
986 Identifier identifier;
987 var scope = in_scope;
988 while (scope != null) {
989 identifier = scope.getIdentifier(symbol, token);
990 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
991 if (identifier != null) {
994 scope = scope.parent;
998 public void printWarnings()
1000 foreach(var w in this.warnings) {