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