JSDOC/Packer.vala
[gnome.introspection-doc-generator] / JSDOC / Packer.vala
1  
2 /**
3  * @namespace JSDOC
4  * @class  Packer
5  * Create a new packer
6  * 
7  * Use with pack.js 
8  * 
9  * 
10  * Usage:
11  * <code>
12  *
13  
14 var x = new  JSON.Packer(target, debugTarget);
15
16 x.files = an array of files
17 x.srcfiles = array of files (that list other files...) << not supported?
18 x.target = "output.pathname.js"
19 x.debugTarget = "output.pathname.debug.js"
20
21
22 x.debugTranslateTarget : "/tmp/output.translate.js" << this used to be the single vs double quotes.. we may not use it in future..
23 x.translateJSON: "/tmp/translate.json",
24     
25 x.packAll();  // writes files  etc..
26     
27  *</code> 
28  *
29  * Notes for improving compacting:
30  *  if you add a jsdoc comment 
31  * <code>
32  * /**
33  *   eval:var:avarname
34  *   eval:var:bvarname
35  *   ....
36  * </code>
37  * directly before an eval statement, it will compress all the code around the eval, 
38  * and not rename the variables 'avarname'
39  * 
40  * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
41  * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
42  * 
43  * 
44  * 
45  * Notes for translation
46  *  - translation relies on you using double quotes for strings if they need translating
47  *  - single quoted strings are ignored.
48  * 
49  * Generation of indexFiles
50  *   - translateIndex = the indexfile
51  * 
52  * 
53  * 
54  * 
55
56  */
57 namespace JSDOC 
58 {
59
60
61         public class Packer : Object 
62         {
63                 /**
64                 * @cfg {String} target to write files to - must be full path.
65                 */
66                 string target;
67                 /**
68                  * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
69                  */
70                 string debugTarget;
71         
72                 /**
73                  * @cfg {String} tmpDir  (optional) where to put the temporary files. 
74                  *      if you set this, then files will not be cleaned up
75                  */
76                 public string tmpDir = "/tmp";  // FIXME??? in ctor?
77         
78         
79                   
80                 /**
81                  * @cfg {Boolean} cleanup  (optional) clean up temp files after done - 
82                  *    Defaults to false if you set tmpDir, otherwise true.
83                  */
84                 public bool cleanup =  true;
85                 
86                 
87                 /**
88                  * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
89                  *    usefull for debugging compressed files.
90                  */
91                 
92                 public bool keepWhite =  true;
93                 
94                 
95                 // list of files to compile...
96                 Gee.ArrayList<string> files;
97                 
98                 public  string out = ""; // if no target is specified - then this will contain the result
99     
100                 public Packer(string target, string debugTarget)
101                 {
102                         this.target = target;
103                         this.debugTarget  = debugTarget;
104                 
105                 }
106                 
107                 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
108                 {
109                         foreach(var f in indexes) {
110                                 this.loadSourceIndex(f);
111                         }
112                 }
113                 
114                 public void loadFiles(Gee.ArrayList<string> fs)
115                 {
116                         foreach(var f in fs) {
117                                 this.files.add(f); //?? easier way?
118                         }
119                 }
120                 
121                 public void pack()
122                 {
123                     if (!this.files) {
124                                 throw new Packer.ArgumentError("No Files loaded before pack() called");
125                         }
126                         this.packAll();
127                 }
128                 
129   
130                 
131                 
132    
133                 
134  
135            
136                 /**
137                  * load a dependancy list -f option
138                  * @param {String} srcfile sourcefile to parse
139                  * 
140                  */
141                 
142                 public void loadSourceIndex(string srcfile)
143                 {
144                     string str;
145                     FileUtils.get_contents(srcfile,out str);
146                     
147                     var lines = str.split("\n");
148                     for(var i =0; i < lines.length;i++) {
149  
150                             var f = lines[i].strip();
151                         if (f.length < 1 ||
152                                 Regex.match_simple ("^\/", f) ||
153                                 !Regex.match_simple ("[a-zA-Z]+", f) 
154                         ){
155                                 continue; // blank comment or not starting with a-z
156                         }
157                         
158                         if (Regex.match_simple ("\.js$", f)) {
159                             this.files.add( f);
160                             // js file..
161                             continue;
162                         }
163                         
164                                 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
165                                 // should we prefix? =- or should this be done elsewhere?
166                                 
167                         var add = f.replace(".", "/") + ".js";
168                         if (_this.files.contains(add)) {
169                             continue;
170                         }
171                         _this.files.add( add );
172                         
173                     }
174                 }
175     
176     
177                 private void packAll()  // do the packing (run from constructor)
178                 {
179                     
180                     //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
181                     //File.write(this.transfile, "");
182                     if (this.target) {
183                         File.write(this.target, "");
184                     }
185                     
186                     if (this.debugTarget) {
187                         File.write(this.debugTarget, "");
188                     }
189                     if (this.debugTranslateTarget) {
190                         File.write(this.debugTarget, "");
191                     }
192                     
193                     for(var i=0; i < this.files.length; i++)  {
194                         var file = this.files[i];
195                         
196                         print("reading " +file );
197                         if (!File.isFile(file)) {
198                             print("SKIP (is not a file) " + file);
199                             continue;
200                         }
201                        
202                         // debug Target
203                         
204                         if (this.debugTarget) {
205                             File.append(this.debugTarget, File.read(file));
206                         }
207                         // it's a good idea to check with 0 compression to see if the code can parse!!
208                         
209                         // debug file..
210                         //File.append(dout, str +"\n"); 
211                         
212                    
213                         
214                         var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
215                         
216                         
217                         // let's see if we have a min file already?
218                         // this might happen if tmpDir is set .. 
219                         if (true && File.exists(minfile)) {
220                             var mt = File.mtime(minfile);
221                             var ot = File.mtime(file);
222                             print("compare : " + mt + "=>" + ot);
223                             if (mt >= ot) {
224                                 continue;
225                                 
226                             }
227                             
228                         }
229                          
230                         print("COMPRESSING ");
231                         //var codeComp = pack(str, 10, 0, 0);
232                         if (File.exists(minfile)) {
233                             File.remove(minfile);
234                         }
235                         var str = File.read(file);
236                         var str = this.packFile(str, file, minfile);
237                          
238                       
239                     }
240                     
241                     
242                     
243                     // if we are translating, write the translations strings at the top
244                     // of the file..
245                     
246                     if (this.translateJSON) {
247                         
248                            
249                         print("MERGING LANGUAGE");
250                         var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
251                         if (this.target) {
252                             File.write(this.target, out);
253                         } else {
254                             this.out += out;
255                         }
256                          
257                         File.write(this.translateJSON, "");
258                         for(var i=0; i < this.files.length; i++)  {
259                             var file = this.files[i];
260                             var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
261                             var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
262                             if (File.exists(transmd5)) {
263                                 var str = File.read(transmd5);
264                                 if (str.length) {
265                                     if (this.target) {
266                                         File.append(this.target, str + "\n");
267                                     } else {
268                                         this.out += str + "\n";
269                                     }
270                                     
271                                 }
272                                 if (this.cleanup) {
273                                     File.remove(transmd5);
274                                 }
275                             }
276                             if (File.exists(transfile)) {
277                                 var str = File.read(transfile);
278                                 if (str.length) {
279                                     File.append(this.translateJSON, str);
280                                 }
281                                 if (this.cleanup) {
282                                     File.remove(transfile);
283                                 }
284                             }
285                             
286                            
287                         }
288                     }
289                     
290                     print("MERGING SOURCE");
291                     
292                     for(var i=0; i < this.files.length; i++)  {
293                         var file = this.files[i];
294                         var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
295                         
296                         
297                         if (!File.exists(minfile)) {
298                             continue;
299                         }
300                         var str = File.read(minfile);
301                         print("using MIN FILE  "+ minfile);
302                         if (str.length) {
303                             if (this.target) {
304                                 File.append(this.target, '//' + file + "\n");   
305                                 File.append(this.target, str + "\n");   
306                             } else {
307                                 this.out += '//' + file + "\n";
308                                 this.out += str + "\n";
309                             }
310                             
311                         }
312                         if (this.cleanup) {
313                             File.remove(minfile);
314                         }
315                         
316                     }
317                     print("Output file: " + this.target);
318                     if (this.debugTarget) print("Output debug file: " + this.debugTarget);
319                     
320                      
321                 
322                 
323                 },
324     /**
325      * Core packing routine  for a file
326      * 
327      * @param str - str source text..
328      * @param fn - filename (for reference?)
329      * @param minfile - min file location...
330      * 
331      */
332     
333     packFile : function (str,fn,minfile)
334     {
335     
336         var tr = new  TokenReader(  { 
337             keepDocs :true, 
338             keepWhite : true,  
339             keepComments : true, 
340             sepIdents : true,
341             collapseWhite : false,
342             filename : fn
343         });
344         this.timerPrint("START" + fn);
345         
346         // we can load translation map here...
347         
348         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
349         
350         // at this point we can write a language file...
351         if (this.translateJSON) {
352             
353             this.writeTranslateFile(fn, minfile, toks);
354         }
355         
356         this.activeFile = fn;
357         
358         // and replace if we are generating a different language..
359         
360         this.timerPrint("Tokenized");
361         //var ts = new TokenStream(toks);
362         //print(JSON.stringify(toks, null,4 )); Seed.quit();
363         var ts = new Collapse(toks);
364        // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
365         //return;//
366         var sp = new ScopeParser(ts);
367         this.timerPrint("Converted to Parser");
368         sp.packer = this;
369         sp.buildSymbolTree();
370         this.timerPrint("Built Sym tree");
371         sp.mungeSymboltree();
372         this.timerPrint("Munged Sym tree");
373         print(sp.warnings.join("\n"));
374         this.timerPrint("Compressed");
375         
376         var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
377         
378         
379         this.timerPrint("Compressed");
380         
381          if (out.length) {
382             File.write(minfile, out);
383             this.timerPrint("Write (" + out.length + "bytes) " + minfile);
384         }
385         
386         return out;
387         
388         
389          
390     },
391     
392     timerPrint: function (str) {
393         var ntime = new Date() * 1;
394         var tdif =  ntime -this.timer;
395         this.timer = ntime;
396         print('['+tdif+']'+str);
397     },
398     
399     /**
400      * 
401      * Translation concept...
402      * -> replace text strings with _T....
403      * -> this file will need inserting at the start of the application....
404      * -> we need to generate 2 files, 
405      * -> a reference used to do the translation, and the _T file..
406      *
407      *
408      * We store the trsum on the token...
409      * 
410      */
411     
412     writeTranslateFile : function(fn, minfile, toks) 
413     {
414         
415         var map = {};  // 'string=> md5sum'
416         var _this = this;
417         var t, last, next;
418         
419         
420         var tokfind =  function (j,dir) {
421             while (1) {
422                 if ((dir < 0) && (j < 0)) {
423                     return false;
424                 }
425                 if ((dir > 0) && (j >= toks.length)) {
426                     return false;
427                 }
428                 j += dir;
429                 if (toks[j].type != 'WHIT') {
430                     return toks[j];
431                 }
432             }
433             return false;
434             
435         }
436         
437         
438         for (var i=0;i<toks.length;i++) {
439             
440             t = toks[i];
441             if (t.type != 'STRN') {
442                 continue;
443             }
444             if (t.name != 'DOUBLE_QUOTE') {
445                 continue;
446             }
447             
448             last = tokfind(i,-1);
449             next = tokfind(i,+1);
450             
451             // we have to ignore key values on objects
452             
453             // defined by
454             // last == '{' or ',' and
455             // next == ':'
456             
457             if (next &&
458                 next.type == 'PUNC' &&
459                 next.data == ':' && 
460                 last && 
461                 last.type == 'PUNC' &&
462                 (last.data == ',' || last.data == '{')
463             ){
464                 continue; // found object key... - we can not translate these
465             }
466                 
467             var sval = t.data.substring(1,t.data.length-1);
468             var ffn = fn.substring(_this.prefix.length);
469             
470             t.trsum = _this.md5(ffn + '-' + sval);
471             map[sval] = t.trsum;
472             
473             
474             
475         }
476         
477         
478         var transfile = minfile + '.lang.trans';
479         var transmd5 = minfile + '.lang';
480         print("writeTranslateFile "  + transfile);
481         var i = 0;
482         var v = '';
483         if (File.exists(transfile)) {
484             File.remove(transfile);
485         }
486         if (File.exists(transmd5)) {
487             File.remove(transmd5);
488         }
489         for(v in map) { i++; break };
490         if (!i ) {
491             return; // no strings in file...
492         }
493         var ffn = fn.substring(this.prefix.length);
494          
495          
496         File.write(transfile, "\n'" + ffn  + "' : {");
497         var l = '';
498         var _tout = {}
499          
500         File.write(transmd5, '');
501         for(v in map) {
502             if (!v.length) {
503                 continue;
504             }
505             File.append(transfile, l + "\n\t\"" + v  + "\" : \"" + v +"\"");
506             l = ',';
507             // strings are raw... - as the where encoded to start with!!!
508             // so we should not need to encode them again.. - just wrap with "
509             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
510         }
511         File.append(transfile, "\n},"); // always one trailing..
512         
513          
514     },
515     md5 : function (string)
516     {
517         
518         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
519         
520     },
521     stringHandler : function(tok)
522     {
523         //print("STRING HANDLER");
524        // callback when outputing compressed file, 
525        var data = tok.data;
526         if (!this.translateJSON) {
527          //   print("TURNED OFF");
528             return data;
529         }
530         if (tok.name == 'SINGLE_QUOTE') {
531             return data;
532         }
533         
534         if (typeof(tok.trsum) == 'undefined') {
535             return data;
536         }
537         
538         return '_T["' + tok.trsum + '"]';
539         
540         var sval = data.substring(1,data.length-1);
541         // we do not clean up... quoting here!??!!?!?!?!?
542         
543         
544         // blank with tabs or spaces..
545         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
546        //     return tok.outData;
547        // }
548         
549         var sval = tok.data.substring(1,data.length-1);
550         var fn = this.activeFile.substring(this.prefix.length);
551         
552         
553         return '_T["' + this.md5(fn + '-' + sval) + '"]';
554         
555         
556     }
557     
558     
559 };