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]);
108 private Packer packer;
110 public ScopeParser(TokenStream ts, Packer packer, string filename) {
111 this.ts = ts; // {TokenStream}
112 this.packer = packer;
113 this.filename = filename;
114 this.warnings = new Gee.ArrayList<string>();
116 this.globalScope = new Scope(-1, null, -1, "", null);
117 this.indexedScopes = new Gee.HashMap<int,Scope>();
119 //this.indexedg = {};
120 //this.timer = new Date() * 1;
126 /*void warn(string s)
128 //print('****************' + s);
129 this.warnings.add(s);
130 //println("WARNING:" + htmlescape(s) + "<BR>");
134 // defaults should not be initialized here =- otherwise they get duped on new, rather than initalized..
141 public void buildSymbolTree()
146 this.braceNesting = 0;
148 // print(JSON.stringify(this.ts.tokens, null,4));
151 this.globalScope =new Scope(-1, null, -1, "", null);
152 this.indexedScopes = new Gee.HashMap<int,Scope>();
153 this.indexedScopes.set(0, this.globalScope );
155 this.mode = ScopeParserMode.BUILDING_SYMBOL_TREE;
157 this.parseScope(this.globalScope);
159 // print("---------------END PASS 1 ---------------- \n");
163 public void mungeSymboltree()
169 // One problem with obfuscation resides in the use of undeclared
170 // and un-namespaced global symbols that are 3 characters or less
171 // in length. Here is an example:
173 // var declaredGlobalVar;
175 // function declaredGlobalFn() {
177 // localvar = abc; // abc is an undeclared global symbol
180 // In the example above, there is a slim chance that localvar may be
181 // munged to 'abc', conflicting with the undeclared global symbol
182 // abc, creating a potential bug. The following code detects such
183 // global symbols. This must be done AFTER the entire file has been
184 // parsed, and BEFORE munging the symbol tree. Note that declaring
185 // extra symbols in the global scope won't hurt.
187 // Note: Since we go through all the tokens to do this, we also use
188 // the opportunity to count how many times each identifier is used.
191 this.braceNesting = 0;
192 this.mode = ScopeParserMode.PASS2_SYMBOL_TREE;
194 //println("MUNGING?");
196 this.parseScope(this.globalScope);
200 this.globalScope.munge();
202 // this.globalScope.dump();
209 void parseScope(Scope scope) // parse a token stream..
211 //this.timerPrint("parseScope EnterScope");
212 //this.log(">>> ENTER SCOPE" + this.scopes.length);
214 var isObjectLitAr = new Gee.ArrayList<bool>();
215 isObjectLitAr.add(false);
219 //var scopeIndent = '';
220 //this.scopes.forEach(function() {
221 // scopeIndent += ' ';
223 //print(">> ENTER SCOPE");
228 var token = this.ts.lookTok(1);
229 while (token != null) {
230 // this.timerPrint("parseScope AFTER lookT: " + token.toString());
231 //this.dumpToken(token , this.scopes, this.braceNesting);
232 //print("SCOPE: %s\n" , token.asString());
233 //this.log(token.data);
234 //if (token.type == 'NAME') {
235 // print('*' + token.data);
243 case TokenName.CONST: // not really relivant as it's only mozzy that does this.
244 //print('SCOPE-VAR:' + token.toString());
246 //this.log("parseScope GOT VAR/CONST : " + token.toString());
248 token = this.ts.nextTok();
249 //!this.debug|| print( token.toString());
250 // print('SCOPE-VAR-VAL:' + JSON.stringify(token, null, 4));
251 if (token == null) { // can return false at EOF!
254 if (token.name == TokenName.VAR || token.data == ",") { // kludge..
257 //this.logR("parseScope GOT VAR : <B>" + token.toString() + "</B>");
258 if (token.type != TokenType.NAME) {
259 this.ts.printRange( int.max(this.ts.cursor-10,0), this.ts.cursor);
260 this.packer.logError(
261 Packer.ResultType.err,
266 //print( "var without ident");
267 //GLib.Process.exit (0);
271 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
272 var identifier = scope.getIdentifier(token.data,token) ;
274 if (identifier == null) {
275 scope.declareIdentifier(token.data, token);
277 token.identifier = identifier;
278 this.packer.logError(
279 Packer.ResultType.warn,
282 "The variable '" +token.data + "' has already been declared in the same scope"
287 token = this.ts.nextTok();
288 //!this.debug|| print(token.toString());
290 assert token.getType() == Token.SEMI ||
291 token.getType() == Token.ASSIGN ||
292 token.getType() == Token.COMMA ||
293 token.getType() == Token.IN;
295 if (token.name == TokenName.IN) {
298 //var bn = this.braceNesting;
299 var bn = this.braceNesting;
300 var nts = new Gee.ArrayList<Token>();
302 if (token == null || token.type == TokenType.VOID || token.data == ",") {
306 token = this.ts.nextTok();
310 this.ts = new TokenStream(nts);
311 this.parseExpression(scope);
315 this.braceNesting = bn;
316 //this.braceNesting = bn;
317 //this.logR("parseScope DONE : <B>ParseExpression</B> - tok is:" + this.ts.lookT(0).toString());
319 token = this.ts.lookTok(1);
321 // print("AFTER EXP: " + token.toString());
322 if (token.data == ";") {
329 //this.ts.dump(vstart , this.ts.cursor);
334 case TokenName.FUNCTION:
335 //if (this.mode == 'BUILDING_SYMBOL_TREE')
336 // print('SCOPE-FUNC:' + JSON.stringify(token,null,4));
337 //println("<i>"+token.data+"</i>");
338 var bn = this.braceNesting;
339 this.parseFunctionDeclaration(scope);
340 this.braceNesting = bn;
344 //print('SCOPE-WITH:' + token.toString());
345 //println("<i>"+token.data+"</i>");
346 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
347 // Inside a 'with' block, it is impossible to figure out
348 // statically whether a symbol is a local variable or an
349 // object member. As a consequence, the only thing we can
350 // do is turn the obfuscation off for the highest scope
351 // containing the 'with' block.
352 this.protectScopeFromObfuscation(scope);
354 this.packer.logError(
355 Packer.ResultType.warn,
358 "Using 'with' is not recommended as it reduces the level of compression"
365 case TokenName.CATCH:
366 //print('SCOPE-CATCH:' + token.toString());
367 //println("<i>"+token.data+"</i>");
368 this.parseCatch(scope);
374 // print(" KEYW = %s\n", token.asString());
377 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
379 if (token.name == TokenName.EVAL) {
380 //print("got token eval...prefix= %s\n", token.prefix);
382 //print(JSON.stringify(token, null,4));
383 // look back one and see if we can find a comment!!!
384 //var prevTok = this.ts.look(-1,true);
385 //print("prev to eval = %s\n", prevTok.asString());
386 //if (prevTok.type == TokenType.COMM) {
387 // print("previus to eval == comment\n%s\n" , prevTok.data);
388 if (token.prefix.length > 0 && Regex.match_simple ("eval",token.prefix)) {
389 // look for eval:var:noreplace\n
392 var regex = new GLib.Regex ("eval:var:([a-z_]+)",GLib.RegexCompileFlags.CASELESS );
394 regex.replace_eval (token.prefix, token.prefix.length, 0, 0, (match_info, result) => {
395 var a = match_info.fetch(1);
396 //print("protect?: %s\n", a);
397 var hi = this.getIdentifier(a, scope, token);
398 // println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
400 //print("PROTECT "+a+" from munge\n");
401 //print(JSON.stringify(hi,null,4));
412 this.protectScopeFromObfuscation(scope);
414 this.packer.logError(
415 Packer.ResultType.warn,
418 "Using 'eval' is not recommended. (use eval:var:noreplace in comments to optimize)"
438 case TokenName.LEFT_CURLY: // {
439 case TokenName.LEFT_PAREN: // (
440 case TokenName.LEFT_BRACE: // [
441 //print("SCOPE-CURLY/PAREN %d / KS= %d / IT=%d \n", token.props.size ,token.keyseq.size, token.items.size);
442 //println("<i>"+token.data+"</i>");
444 if (token.props.size > 0) {
446 // { a : ... , c : .... }
448 for (var i = 0;i < token.keyseq.size; i++ ){
449 //var iter = token.props.map_iterator();
450 var k = token.keyseq.get(i);
452 TokenKeyMap val = token.props.get(k);
453 //print("SCOPE-PROPS GET (%d/%d): %s\n", i, token.keyseq.size,k);
455 // print('SCOPE-PROPS:' + JSON.stringify(token.props[prop],null,4));
456 if (val == null || val.vals.size < 1) {
459 if (val.vals.get(0).data == "function") {
460 // parse a function..
461 this.ts = new TokenStream(val.vals);
463 this.parseFunctionDeclaration(scope);
469 this.ts = new TokenStream(val.vals);
470 this.parseExpression(scope);
475 // it's an object literal..
476 // the values could be replaced..
480 // ( ... ) or { .... } not object literals..
483 for (var xx =0; xx < token.items.size; xx++) {
484 var expr = token.items.get(xx);
485 //token.items.forEach(function(expr) {
486 //print(expr.toString());
487 this.ts = new TokenStream(expr);
488 //if (curTS.data == '(') {
489 this.parseScope(scope);
491 // _this.parseExpression(scope)
496 //print("NOT PROPS"); Seed.quit();
498 //isObjectLitAr.push(false);
499 //this.braceNesting++;
501 //print(">>>>>> OBJLIT PUSH(false)" + this.braceNesting);
504 case TokenName.RIGHT_CURLY: // }
505 //print("<< EXIT SCOPE");
515 ///case "STRN.DOUBLE_QUOTE": // used for object lit detection.. case "STRN.SINGLE_QUOTE":
516 // print('SCOPE-STRING:' + token.toString());
517 //println("<i>"+token.data+"</i>");
519 if (this.ts.lookTok(-1).data == "{" && this.ts.lookTok(1).data == ":") {
520 // then we are in an object lit.. -> we need to flag the brace as such...
521 isObjectLitAr.remove_at(isObjectLitAr.size-1);
522 isObjectLitAr.add(true);
523 //print(">>>>>> OBJLIT REPUSH(true)");
525 var isInObjectLitAr = isObjectLitAr.get(isObjectLitAr.size-1);
527 if (isInObjectLitAr && this.ts.lookTok(1).data == ":" &&
528 ( this.ts.lookTok(-1).data == "{" || this.ts.lookTok(-1).data == ":" )) {
529 // see if we can replace..
530 // remove the quotes..
531 // should do a bit more checking!!!! (what about wierd char's in the string..
532 var str = token.data.substring(1,token.data.length-1);
534 if (Regex.match_simple ("^[a-z_]+$", str,GLib.RegexCompileFlags.CASELESS) && ScopeParser.idents.index_of(str) < 0) {
545 // print("SCOPE got NAME:%s\n" , token.asString());
546 //print("DEAL WITH NAME:");
548 // look for { ** : <- indicates obj literal.. ** this could occur with numbers ..
549 // skip anyting with "." before it..!!
550 // print("prev0 = " + this.ts.lookTok(0).asString() +"\n");
551 // print("prev-1 = " + this.ts.lookTok(-1).asString() +"\n");
552 if (this.ts.lookTok(-1).name == TokenName.DOT) {
553 // skip, it's an object prop.
554 // print("prev is a .dot.\n");
555 //println("<i>"+token.data+"</i>");
558 //print("SYMBOL: " + token.toString());
560 var symbol = token.data;
561 if (symbol == "this") {
562 // print("ignore 'this'\n");
566 if (this.mode == ScopeParserMode.PASS2_SYMBOL_TREE) {
568 //println("GOT IDENT: -2 : " + this.ts.lookT(-2).toString() + " <BR> ..... -1 : " + this.ts.lookT(-1).toString() + " <BR> ");
570 //print ("MUNGE?" + symbol);
572 //println("GOT IDENT: <B>" + symbol + "</B><BR/>");
574 //println("GOT IDENT (2): <B>" + symbol + "</B><BR/>");
575 var identifier = this.getIdentifier(symbol, scope, token);
578 if (identifier == null) {
579 // BUG!find out where builtin is defined...
580 // print("new identifier\n");
581 if (symbol.length <= 3 && Scope.builtin.index_of(symbol) < 0) {
582 // Here, we found an undeclared and un-namespaced symbol that is
583 // 3 characters or less in length. Declare it in the global scope.
584 // We don't need to declare longer symbols since they won't cause
585 // any conflict with other munged symbols.
586 this.globalScope.declareIdentifier(symbol, token);
588 this.packer.logError(
589 Packer.ResultType.warn,
592 "Found an undeclared symbol: " + symbol
597 //println("GOT IDENT IGNORE(3): <B>" + symbol + "</B><BR/>");
599 // print("existing identifier\n");
600 token.identifier = identifier;
601 identifier.refcount++;
606 //println("<B>SID</B>");
615 //print("parseScope TOK : " + token.toString());
616 token = this.ts.nextTok();
617 //if (this.ts.nextT()) break;
620 //print("<<< EXIT SCOPE");
621 //print("<<<<<<<EXIT SCOPE ERR?" +this.scopes.length);
626 void parseExpression(Scope scope)
629 // Parse the expression until we encounter a comma or a semi-colon
630 // in the same brace nesting, bracket nesting and paren nesting.
631 // Parse functions if any...
632 //println("<i>EXP</i><BR/>");
633 //!this.debug || print("PARSE EXPR");
636 // for printing stuff..
641 //var expressionBraceNesting = this.braceNesting + 0;
642 //var bracketNesting = 0;
643 //var parensNesting = 0;
645 var isObjectLitAr = new Gee.ArrayList<bool>();
646 isObjectLitAr.add( false);
651 //print(scopeIndent + ">> ENTER EXPRESSION" + this.expN);
652 while (null != (token = this.ts.nextTok())) {
657 // moved out of loop?
658 currentScope = this.scopes[this.scopes.length-1];
660 var scopeIndent = '';
661 this.scopes.forEach(function() {
666 //this.dumpToken(token, this.scopes, this.braceNesting );
667 //print("EXPR %s\n" , token.asString());
670 //println("<i>"+token.data+"</i>");
671 //this.log("EXP:" + token.data);
672 switch (token.type) {
674 //print("EXPR-PUNC:" + token.toString());
679 //print("<< EXIT EXPRESSION");
687 case "(": //Token.LP:
688 case "{": //Token.LC:
689 case "[": //Token.LB:
690 //print('SCOPE-CURLY/PAREN/BRACE:' + token.toString());
691 // print('SCOPE-CURLY/PAREN/BRACE:' + JSON.stringify(token, null,4));
692 //println("<i>"+token.data+"</i>");
694 if (token.keyseq.size > 0) {
696 for (var i = 0;i < token.keyseq.size; i++ ){
697 //var iter = token.props.map_iterator();
698 var k = token.keyseq.get(i);
700 TokenKeyMap val = token.props.get(k);
703 print("failed to get %s val from token %s\n", k, token.asString());
707 //if (val.vals.size < 1) {
708 //print(JSON.stringify(token.props, null,4));
712 if (val.vals.size > 0 && val.vals.get(0).data == "function") {
713 // parse a function..
714 this.ts = new TokenStream(val.vals);
716 this.parseFunctionDeclaration(scope);
721 this.ts = new TokenStream(val.vals);
722 this.parseExpression(scope);
727 // it's an object literal..
728 // the values could be replaced..
734 foreach(var expr in token.items) {
736 this.ts = new TokenStream(expr);
737 this.parseExpression(scope);
743 ///print(">>>>> EXP PUSH(false)"+this.braceNesting);
750 case ")": //Token.RP:
751 case "]": //Token.RB:
752 case "}": //Token.RB:
753 //print("<< EXIT EXPRESSION");
766 case TokenType.STRN: // used for object lit detection..
767 //if (this.mode == 'BUILDING_SYMBOL_TREE')
768 //print("EXPR-STR:" + JSON.stringify(token, null, 4));
776 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
778 //print("EXPR-NAME:" + JSON.stringify(token, null, 4));
780 //print("EXPR-NAME:" + token.toString());
782 var symbol = token.data;
783 //print("expression got NAME = %s \n" , symbol);
784 //print("in NAME 0: " + this.ts.look(0).toString());
785 //print("in NAME 2: " + this.ts.lookTok(2).toString());
787 //print(this.ts.lookTok(-1).data);
789 if (this.ts.lookTok(-1).data == ".") {
793 if (symbol == "this") {
797 if (this.mode == ScopeParserMode.PASS2_SYMBOL_TREE) {
799 var identifier = this.getIdentifier(symbol, scope, token);
800 //println("<B>??</B>");
801 if (identifier == null) {
803 if (symbol.length <= 3 && Scope.builtin.index_of(symbol) < 0) {
804 // Here, we found an undeclared and un-namespaced symbol that is
805 // 3 characters or less in length. Declare it in the global scope.
806 // We don't need to declare longer symbols since they won't cause
807 // any conflict with other munged symbols.
808 this.globalScope.declareIdentifier(symbol, token);
810 this.packer.logError(
811 Packer.ResultType.warn,
814 "Found an undeclared symbol: " + symbol
820 //print("Found an undeclared symbol: " + symbol + ' (line:' + token.line + ')');
823 //print("undeclared:" + token.toString())
828 //println("<B>++</B>");
829 token.identifier = identifier;
830 identifier.refcount++;
839 //println("<B>EID</B>");
841 //if (this.mode == 'BUILDING_SYMBOL_TREE')
842 // print("EXPR-KEYW:" + JSON.stringify(token, null, 4));
844 //print('EXPR-KEYW:' + token.toString());
845 if (token.name == TokenName.FUNCTION) {
847 this.parseFunctionDeclaration(scope);
852 var symbol = token.data;
853 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
855 if (token.name == TokenName.EVAL) {
858 //print(JSON.stringify(token,null,4));
860 if (token.prefix.length > 0 && Regex.match_simple ("eval:var:", token.prefix,GLib.RegexCompileFlags.CASELESS)) {
861 // look for eval:var:noreplace\n
862 // print("GOT MATCH?");
865 var regex = new GLib.Regex ("eval:var:([a-z_]+)",GLib.RegexCompileFlags.CASELESS );
867 regex.replace_eval (token.prefix, token.prefix.length, 0, 0, (match_info, result) => {
868 var a = match_info.fetch(0);
869 //print("PROTECT: " + a);
872 var hi = this.getIdentifier(a, scope, token);
873 //println("PROTECT "+a+" from munge" + (hi ? "FOUND" : "MISSING"));
875 // println("PROTECT "+a+" from munge");
883 this.protectScopeFromObfuscation(scope);
885 this.packer.logError(
886 Packer.ResultType.warn,
889 "Using 'eval' is not recommended. use eval:var in comment before eval to enable compression " + symbol
902 //if (this.mode == 'BUILDING_SYMBOL_TREE')
903 // print("EXPR-SKIP:" + JSON.stringify(token, null, 4));
908 //print("<< EXIT EXPRESSION");
913 void parseCatch(Scope scope) {
916 //token = getToken(-1);
917 //assert token.getType() == Token.CATCH;
918 var token = this.ts.nextTok();
919 token = this.ts.nextTok();
922 //print(JSON.stringify(this.ts,null,4));
923 //assert token.getType() == Token.LP; (
924 //token = this.ts.nextTok();
925 //assert token.getType() == Token.NAME;
927 var symbol = token.items[0][0].data;
930 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
931 // We must declare the exception identifier in the containing function
932 // scope to avoid errors related to the obfuscation process. No need to
933 // display a warning if the symbol was already declared here...
934 scope.declareIdentifier(symbol, token.items[0][0]);
936 //?? why inc the refcount?? - that should be set when building the tree???
937 var identifier = this.getIdentifier(symbol, scope, token.items[0][0]);
938 identifier.refcount++;
941 //token = this.ts.nextTok();
942 //assert token.getType() == Token.RP; // )
945 void parseFunctionDeclaration (Scope scope)
947 //print("PARSE FUNCTION");
950 // var b4braceNesting = this.braceNesting + 0;
952 //this.logR("<B>PARSING FUNCTION</B>");
955 var token = this.ts.nextTok();
956 if (token.type == TokenType.NAME) {
957 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
958 // Get the name of the function and declare it in the current scope.
959 var symbol = token.data;
960 if (scope.getIdentifier(symbol,token) != null) {
963 this.packer.logError(
964 Packer.ResultType.warn,
967 "The function " + symbol + " has already been declared in the same scope..."
973 scope.declareIdentifier(symbol,token);
975 token = this.ts.nextTok();
979 // return function() {....
980 while (token.data != "(") {
981 //print(token.toString());
982 token = this.ts.nextTok();
987 //assert token.getType() == Token.LP;
988 if (this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
989 fnScope = new Scope(1, scope, token.id, "", token);
991 //println("STORING SCOPE" + this.ts.cursor);
993 this.indexedScopes.set(token.id,fnScope);
996 //qln("FETCHING SCOPE" + this.ts.cursor);
997 fnScope = this.indexedScopes[token.id];
999 //if (this.mode == 'BUILDING_SYMBOL_TREE')
1000 // print('FUNC-PARSE:' + JSON.stringify(token,null,4));
1001 // Parse function arguments.
1002 var args = token.items;
1003 for (var argpos =0; argpos < args.size; argpos++) {
1005 token = args.get(argpos).get(0);
1006 //print ("FUNC ARGS: " + token.toString())
1007 //assert token.getType() == Token.NAME ||
1008 // token.getType() == Token.COMMA;
1009 if (token.type == TokenType.NAME && this.mode == ScopeParserMode.BUILDING_SYMBOL_TREE) {
1010 var symbol = token.data;
1011 var identifier = fnScope.declareIdentifier(symbol,token);
1012 if (symbol == "$super" && argpos == 0) {
1013 // Exception for Prototype 1.6...
1014 identifier.toMunge = false;
1020 token = this.ts.nextTok();
1021 if (token == null) {
1024 //print('FUNC-BODY:' + JSON.stringify(token.items,null,4));
1026 //print(token.toString());
1027 // assert token.getType() == Token.LC;
1028 //this.braceNesting++;
1030 //token = this.ts.nextTok();
1031 //print(token.toString());
1032 var outTS = this.ts;
1033 foreach(var tar in token.items) {
1034 this.ts = new TokenStream(tar);
1035 this.parseScope(fnScope);
1039 //print(JSON.stringify(this.ts,null,4));
1040 //this.parseScope(fnScope);
1042 // now pop it off the stack!!!
1044 //this.braceNesting = b4braceNesting;
1045 //print("ENDFN -1: " + this.ts.lookTok(-1).toString());
1046 //print("ENDFN 0: " + this.ts.lookTok(0).toString());
1047 //print("ENDFN 1: " + this.ts.lookTok(1).toString());
1050 void protectScopeFromObfuscation (Scope scope) {
1051 //assert scope != null;
1053 if (scope == this.globalScope) {
1054 // The global scope does not get obfuscated,
1055 // so we don't need to worry about it...
1059 // Find the highest local scope containing the specified scope.
1060 while (scope != null && scope.parent != this.globalScope) {
1061 scope = scope.parent;
1064 //assert scope.getParentScope() == globalScope;
1065 scope.preventMunging();
1068 Identifier? getIdentifier(string symbol, Scope in_scope, Token token)
1070 Identifier identifier;
1071 var scope = in_scope;
1072 while (scope != null) {
1073 identifier = scope.getIdentifier(symbol, token);
1074 //println("ScopeParser.getIdentgetUsedSymbols("+symbol+")=" + scope.getUsedSymbols().join(','));
1075 if (identifier != null) {
1078 scope = scope.parent;
1082 public void printWarnings()
1084 foreach(var w in this.warnings) {