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                 FileOutputStream targetStream;
121                 FileOutputStream targetDebugStream;
122                 
123                 public void pack()
124                 {
125                     if (!this.files) {
126                                 throw new Packer.ArgumentError("No Files loaded before pack() called");
127                         }
128                         
129                         
130                         this.packAll();
131                 }
132                 
133   
134                 
135                 
136    
137                 
138  
139            
140                 /**
141                  * load a dependancy list -f option
142                  * @param {String} srcfile sourcefile to parse
143                  * 
144                  */
145                 
146                 public void loadSourceIndex(string srcfile)
147                 {
148                     string str;
149                     FileUtils.get_contents(srcfile,out str);
150                     
151                     var lines = str.split("\n");
152                     for(var i =0; i < lines.length;i++) {
153  
154                             var f = lines[i].strip();
155                         if (f.length < 1 ||
156                                 Regex.match_simple ("^\/", f) ||
157                                 !Regex.match_simple ("[a-zA-Z]+", f) 
158                         ){
159                                 continue; // blank comment or not starting with a-z
160                         }
161                         
162                         if (Regex.match_simple ("\.js$", f)) {
163                             this.files.add( f);
164                             // js file..
165                             continue;
166                         }
167                         
168                                 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
169                                 // should we prefix? =- or should this be done elsewhere?
170                                 
171                         var add = f.replace(".", "/") + ".js";
172                         if (_this.files.contains(add)) {
173                             continue;
174                         }
175                         _this.files.add( add );
176                         
177                     }
178                 }
179                 
180     
181                 private void packAll()  // do the packing (run from constructor)
182                 {
183                     
184                     //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
185                     //File.write(this.transfile, "");
186                     if (this.target.length) {
187                         File.write(this.target, "");
188                     }
189                     
190                     if (this.debugTarget) {
191                         File.write(this.debugTarget, "");
192                     }
193                     if (this.debugTranslateTarget) {
194                         File.write(this.debugTarget, "");
195                     }
196                     
197                     for(var i=0; i < this.files.length; i++)  {
198                         var file = this.files[i];
199                         
200                         print("reading " +file );
201                         if (!File.isFile(file)) {
202                             print("SKIP (is not a file) " + file);
203                             continue;
204                         }
205                        
206                         // debug Target
207                         
208                         if (this.debugTarget) {
209                             File.append(this.debugTarget, File.read(file));
210                         }
211                         // it's a good idea to check with 0 compression to see if the code can parse!!
212                         
213                         // debug file..
214                         //File.append(dout, str +"\n"); 
215                         
216                    
217                         
218                         var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
219                         
220                         
221                         // let's see if we have a min file already?
222                         // this might happen if tmpDir is set .. 
223                         if (true && File.exists(minfile)) {
224                             var mt = File.mtime(minfile);
225                             var ot = File.mtime(file);
226                             print("compare : " + mt + "=>" + ot);
227                             if (mt >= ot) {
228                                 continue;
229                                 
230                             }
231                             
232                         }
233                          
234                         print("COMPRESSING ");
235                         //var codeComp = pack(str, 10, 0, 0);
236                         if (File.exists(minfile)) {
237                             File.remove(minfile);
238                         }
239                         var str = File.read(file);
240                         var str = this.packFile(str, file, minfile);
241                          
242                       
243                     }
244                     
245                     
246                     
247                     // if we are translating, write the translations strings at the top
248                     // of the file..
249                     
250                     if (this.translateJSON) {
251                         
252                            
253                         print("MERGING LANGUAGE");
254                         var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
255                         if (this.target) {
256                             File.write(this.target, out);
257                         } else {
258                             this.out += out;
259                         }
260                          
261                         File.write(this.translateJSON, "");
262                         for(var i=0; i < this.files.length; i++)  {
263                             var file = this.files[i];
264                             var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
265                             var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
266                             if (File.exists(transmd5)) {
267                                 var str = File.read(transmd5);
268                                 if (str.length) {
269                                     if (this.target) {
270                                         File.append(this.target, str + "\n");
271                                     } else {
272                                         this.out += str + "\n";
273                                     }
274                                     
275                                 }
276                                 if (this.cleanup) {
277                                     File.remove(transmd5);
278                                 }
279                             }
280                             if (File.exists(transfile)) {
281                                 var str = File.read(transfile);
282                                 if (str.length) {
283                                     File.append(this.translateJSON, str);
284                                 }
285                                 if (this.cleanup) {
286                                     File.remove(transfile);
287                                 }
288                             }
289                             
290                            
291                         }
292                     }
293                     
294                     print("MERGING SOURCE");
295                     
296                     for(var i=0; i < this.files.length; i++)  {
297                         var file = this.files[i];
298                         var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
299                         
300                         
301                         if (!File.exists(minfile)) {
302                             continue;
303                         }
304                         var str = File.read(minfile);
305                         print("using MIN FILE  "+ minfile);
306                         if (str.length) {
307                             if (this.target) {
308                                 File.append(this.target, '//' + file + "\n");   
309                                 File.append(this.target, str + "\n");   
310                             } else {
311                                 this.out += '//' + file + "\n";
312                                 this.out += str + "\n";
313                             }
314                             
315                         }
316                         if (this.cleanup) {
317                             File.remove(minfile);
318                         }
319                         
320                     }
321                     print("Output file: " + this.target);
322                     if (this.debugTarget) print("Output debug file: " + this.debugTarget);
323                     
324                      
325                 
326                 
327                 },
328     /**
329      * Core packing routine  for a file
330      * 
331      * @param str - str source text..
332      * @param fn - filename (for reference?)
333      * @param minfile - min file location...
334      * 
335      */
336     
337     packFile : function (str,fn,minfile)
338     {
339     
340         var tr = new  TokenReader(  { 
341             keepDocs :true, 
342             keepWhite : true,  
343             keepComments : true, 
344             sepIdents : true,
345             collapseWhite : false,
346             filename : fn
347         });
348         this.timerPrint("START" + fn);
349         
350         // we can load translation map here...
351         
352         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
353         
354         // at this point we can write a language file...
355         if (this.translateJSON) {
356             
357             this.writeTranslateFile(fn, minfile, toks);
358         }
359         
360         this.activeFile = fn;
361         
362         // and replace if we are generating a different language..
363         
364         this.timerPrint("Tokenized");
365         //var ts = new TokenStream(toks);
366         //print(JSON.stringify(toks, null,4 )); Seed.quit();
367         var ts = new Collapse(toks);
368        // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
369         //return;//
370         var sp = new ScopeParser(ts);
371         this.timerPrint("Converted to Parser");
372         sp.packer = this;
373         sp.buildSymbolTree();
374         this.timerPrint("Built Sym tree");
375         sp.mungeSymboltree();
376         this.timerPrint("Munged Sym tree");
377         print(sp.warnings.join("\n"));
378         this.timerPrint("Compressed");
379         
380         var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
381         
382         
383         this.timerPrint("Compressed");
384         
385          if (out.length) {
386             File.write(minfile, out);
387             this.timerPrint("Write (" + out.length + "bytes) " + minfile);
388         }
389         
390         return out;
391         
392         
393          
394     },
395     
396     timerPrint: function (str) {
397         var ntime = new Date() * 1;
398         var tdif =  ntime -this.timer;
399         this.timer = ntime;
400         print('['+tdif+']'+str);
401     },
402     
403     /**
404      * 
405      * Translation concept...
406      * -> replace text strings with _T....
407      * -> this file will need inserting at the start of the application....
408      * -> we need to generate 2 files, 
409      * -> a reference used to do the translation, and the _T file..
410      *
411      *
412      * We store the trsum on the token...
413      * 
414      */
415     
416     writeTranslateFile : function(fn, minfile, toks) 
417     {
418         
419         var map = {};  // 'string=> md5sum'
420         var _this = this;
421         var t, last, next;
422         
423         
424         var tokfind =  function (j,dir) {
425             while (1) {
426                 if ((dir < 0) && (j < 0)) {
427                     return false;
428                 }
429                 if ((dir > 0) && (j >= toks.length)) {
430                     return false;
431                 }
432                 j += dir;
433                 if (toks[j].type != 'WHIT') {
434                     return toks[j];
435                 }
436             }
437             return false;
438             
439         }
440         
441         
442         for (var i=0;i<toks.length;i++) {
443             
444             t = toks[i];
445             if (t.type != 'STRN') {
446                 continue;
447             }
448             if (t.name != 'DOUBLE_QUOTE') {
449                 continue;
450             }
451             
452             last = tokfind(i,-1);
453             next = tokfind(i,+1);
454             
455             // we have to ignore key values on objects
456             
457             // defined by
458             // last == '{' or ',' and
459             // next == ':'
460             
461             if (next &&
462                 next.type == 'PUNC' &&
463                 next.data == ':' && 
464                 last && 
465                 last.type == 'PUNC' &&
466                 (last.data == ',' || last.data == '{')
467             ){
468                 continue; // found object key... - we can not translate these
469             }
470                 
471             var sval = t.data.substring(1,t.data.length-1);
472             var ffn = fn.substring(_this.prefix.length);
473             
474             t.trsum = _this.md5(ffn + '-' + sval);
475             map[sval] = t.trsum;
476             
477             
478             
479         }
480         
481         
482         var transfile = minfile + '.lang.trans';
483         var transmd5 = minfile + '.lang';
484         print("writeTranslateFile "  + transfile);
485         var i = 0;
486         var v = '';
487         if (File.exists(transfile)) {
488             File.remove(transfile);
489         }
490         if (File.exists(transmd5)) {
491             File.remove(transmd5);
492         }
493         for(v in map) { i++; break };
494         if (!i ) {
495             return; // no strings in file...
496         }
497         var ffn = fn.substring(this.prefix.length);
498          
499          
500         File.write(transfile, "\n'" + ffn  + "' : {");
501         var l = '';
502         var _tout = {}
503          
504         File.write(transmd5, '');
505         for(v in map) {
506             if (!v.length) {
507                 continue;
508             }
509             File.append(transfile, l + "\n\t\"" + v  + "\" : \"" + v +"\"");
510             l = ',';
511             // strings are raw... - as the where encoded to start with!!!
512             // so we should not need to encode them again.. - just wrap with "
513             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
514         }
515         File.append(transfile, "\n},"); // always one trailing..
516         
517          
518     },
519     md5 : function (string)
520     {
521         
522         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
523         
524     },
525     stringHandler : function(tok)
526     {
527         //print("STRING HANDLER");
528        // callback when outputing compressed file, 
529        var data = tok.data;
530         if (!this.translateJSON) {
531          //   print("TURNED OFF");
532             return data;
533         }
534         if (tok.name == 'SINGLE_QUOTE') {
535             return data;
536         }
537         
538         if (typeof(tok.trsum) == 'undefined') {
539             return data;
540         }
541         
542         return '_T["' + tok.trsum + '"]';
543         
544         var sval = data.substring(1,data.length-1);
545         // we do not clean up... quoting here!??!!?!?!?!?
546         
547         
548         // blank with tabs or spaces..
549         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
550        //     return tok.outData;
551        // }
552         
553         var sval = tok.data.substring(1,data.length-1);
554         var fn = this.activeFile.substring(this.prefix.length);
555         
556         
557         return '_T["' + this.md5(fn + '-' + sval) + '"]';
558         
559         
560     }
561     
562     
563 };