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