amberc.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. /**
  2. * This is a "compiler" for Amber code.
  3. * Create and run it the following way:
  4. * var amberc = new AmberC();
  5. * amberc.main();
  6. *
  7. * Execute the JS file without arguments or with -h / --help for help.
  8. */
  9. /**
  10. * Map the async filter function onto array and evaluate callback, once all have finished.
  11. * Taken from: http://howtonode.org/control-flow-part-iii
  12. */
  13. function map(array, filter, callback) {
  14. var counter = array.length;
  15. var new_array = [];
  16. array.forEach(function (item, index) {
  17. filter(item, function (err, result) {
  18. if (err) { callback(err); return; }
  19. new_array[index] = result;
  20. counter--;
  21. if (counter === 0) {
  22. callback(null, new_array);
  23. }
  24. });
  25. });
  26. }
  27. /**
  28. * Always evaluates the callback parameter.
  29. * Used by Combo blocks to always call the next function,
  30. * even if all of the other functions did not run.
  31. */
  32. function always_resolve(callback) {
  33. callback();
  34. }
  35. /**
  36. * Combine several async functions and evaluate callback once all of them have finished.
  37. * Taken from: http://howtonode.org/control-flow
  38. */
  39. function Combo(callback) {
  40. this.callback = callback;
  41. this.items = 0;
  42. this.results = [];
  43. }
  44. Combo.prototype = {
  45. add: function () {
  46. var self = this,
  47. id = this.items;
  48. this.items++;
  49. return function () {
  50. self.check(id, arguments);
  51. };
  52. },
  53. check: function (id, arguments) {
  54. this.results[id] = Array.prototype.slice.call(arguments);
  55. this.items--;
  56. if (this.items == 0) {
  57. this.callback.apply(this, this.results);
  58. }
  59. }
  60. };
  61. var path = require('path'),
  62. util = require('util'),
  63. fs = require('fs'),
  64. exec = require('child_process').exec;
  65. console.time('Compile Time');
  66. function AmberC() {
  67. // Get Amber root directory from the location of this script so that
  68. // we can find the st and js directories etc.
  69. this.amber_dir = path.normalize( path.join(path.dirname(process.argv[1]), '..') );
  70. this.kernel_libraries = ['boot', 'Kernel-Objects', 'Kernel-Classes', 'Kernel-Methods',
  71. 'Kernel-Collections', 'Kernel-Exceptions', 'Kernel-Transcript',
  72. 'Kernel-Announcements'];
  73. this.compiler_libraries = this.kernel_libraries.concat(['parser', 'Compiler',
  74. 'Compiler-Exceptions']);
  75. //, 'Compiler-Core', 'Compiler-AST', 'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic'];
  76. this.closure_jar = path.resolve(path.join(process.env['HOME'], 'compiler.jar'));
  77. }
  78. /**
  79. * Default values.
  80. */
  81. var createDefaults = function(amber_dir){
  82. return {
  83. 'smalltalk': {}, // the evaluated compiler will be stored in this variable (see create_compiler)
  84. 'load': [],
  85. 'init': path.join(amber_dir, 'js', 'init.js'),
  86. 'main': undefined,
  87. 'mainfile': undefined,
  88. 'closure': false,
  89. 'closure_parts': false,
  90. 'closure_full': false,
  91. 'closure_options': '',
  92. 'suffix': '',
  93. 'loadsuffix': '',
  94. 'suffix_used': '',
  95. 'deploy': false,
  96. 'libraries': [],
  97. 'compile': [],
  98. 'compiled_categories': [],
  99. 'compiled': [],
  100. 'program': undefined
  101. };
  102. };
  103. /**
  104. * Main function for executing the compiler.
  105. */
  106. AmberC.prototype.main = function(parameters) {
  107. var options = parameters || process.argv.slice(2);
  108. if (1 > options.length) {
  109. this.usage();
  110. } else {
  111. this.defaults = createDefaults(this.amber_dir);
  112. this.handle_options(options);
  113. }
  114. };
  115. /**
  116. * Process given program options and update defaults values.
  117. * Followed by check_for_closure_compiler() and then collect_files().
  118. */
  119. AmberC.prototype.handle_options = function(optionsArray) {
  120. var stFiles = [];
  121. var jsFiles = [];
  122. var programName = [];
  123. var currentItem = optionsArray.shift();
  124. var defaults = this.defaults;
  125. while(undefined !== currentItem) {
  126. switch(currentItem) {
  127. case '-l':
  128. defaults.load.push.apply(defaults.load, optionsArray.shift().split(','));
  129. break;
  130. case '-i':
  131. defaults.init = optionsArray.shift();
  132. break;
  133. case '-m':
  134. defaults.main = optionsArray.shift();
  135. break;
  136. case '-M':
  137. defaults.mainfile = optionsArray.shift();
  138. break;
  139. case '-o':
  140. defaults.closure = true;
  141. defaults.closure_parts = true;
  142. break;
  143. case '-O':
  144. defaults.closure = true;
  145. defaults.closure_full = true;
  146. break;
  147. case '-A':
  148. defaults.closure = true;
  149. defaults.closure_options = defaults.closure_options + ' --compilation_level ADVANCED_OPTIMIZATIONS';
  150. defaults.closure_full = true;
  151. break;
  152. case '-d':
  153. defaults.deploy = true;
  154. break;
  155. case '-s':
  156. defaults.suffix = optionsArray.shift();
  157. defaults.suffix_used = defaults.suffix;
  158. break;
  159. case '-S':
  160. defaults.loadsuffix = optionsArray.shift();
  161. defaults.suffix_used = defaults.suffix;
  162. break;
  163. case '-h':
  164. case '--help':
  165. case '?':
  166. this.usage();
  167. break;
  168. default:
  169. var fileSuffix = path.extname(currentItem);
  170. switch (fileSuffix) {
  171. case '.st':
  172. stFiles.push(currentItem);
  173. break;
  174. case '.js':
  175. jsFiles.push(currentItem);
  176. break;
  177. default:
  178. // Will end up being the last non js/st argument
  179. programName.push(currentItem);
  180. break;
  181. };
  182. };
  183. currentItem = optionsArray.shift();
  184. }
  185. if(1 < programName.length) {
  186. throw new Error('More than one name for ProgramName given: ' + programName);
  187. } else {
  188. defaults.program = programName[0];
  189. }
  190. var self = this;
  191. this.check_for_closure_compiler(function(){
  192. self.collect_files(stFiles, jsFiles)
  193. });
  194. };
  195. /**
  196. * Print usage options and exit.
  197. */
  198. AmberC.prototype.usage = function() {
  199. console.log('Usage: amberc [-l lib1,lib2...] [-i init_file] [-m main_class] [-M main_file]');
  200. console.log(' [-o] [-O|-A] [-d] [-s suffix] [-S suffix] [file1 [file2 ...]] [Program]');
  201. console.log('');
  202. console.log(' amberc compiles Amber files - either separately or into a complete runnable');
  203. console.log(' program. If no .st files are listed only a linking stage is performed.');
  204. console.log(' Files listed will be handled using the following rules:');
  205. console.log('');
  206. console.log(' *.js');
  207. console.log(' Files are linked (concatenated) in listed order.');
  208. console.log(' If not found we look in $AMBER/js/');
  209. console.log('');
  210. console.log(' *.st');
  211. console.log(' Files are compiled into .js files before concatenation.');
  212. console.log(' If not found we look in $AMBER/st/.');
  213. console.log('');
  214. console.log(' NOTE: Each .st file is currently considered to be a fileout of a single class');
  215. console.log(' category of the same name as the file!');
  216. console.log('');
  217. console.log(' If no <Program> is specified each given .st file will be compiled into');
  218. console.log(' a matching .js file. Otherwise a <Program>.js file is linked together based on');
  219. console.log(' the given options:');
  220. console.log(' -l library1,library2');
  221. console.log(' Add listed JavaScript libraries in listed order.');
  222. console.log(' Libraries are not separated by spaces or end with .js.');
  223. console.log('');
  224. console.log(' -i init_file');
  225. console.log(' Add library initializer <init_file> instead of default $AMBER/js/init.js ');
  226. console.log('');
  227. console.log(' -m main_class');
  228. console.log(' Add a call to the class method main_class>>main at the end of <Program>.');
  229. console.log('');
  230. console.log(' -M main_file');
  231. console.log(' Add <main_file> at the end of <Program.js> acting as #main.');
  232. console.log('');
  233. console.log(' -o');
  234. console.log(' Optimize each .js file using the Google closure compiler.');
  235. console.log(' Using Closure compiler found at ~/compiler.jar');
  236. console.log('');
  237. console.log(' -O');
  238. console.log(' Optimize final <Program>.js using the Google closure compiler.');
  239. console.log(' Using Closure compiler found at ~/compiler.jar');
  240. console.log('');
  241. console.log(' -A Same as -O but use --compilation_level ADVANCED_OPTIMIZATIONS');
  242. console.log('');
  243. console.log(' -d');
  244. console.log(' Additionally export code for deploy - stripped from source etc.');
  245. console.log(' Uses suffix ".deploy.js" in addition to any explicit suffic set by -s.');
  246. console.log('');
  247. console.log(' -s suffix');
  248. console.log(' Add <suffix> to compiled .js files. File.st is then compiled into');
  249. console.log(' File.<suffix>.js.');
  250. console.log('');
  251. console.log(' -S suffix');
  252. console.log(' Use <suffix> for all libraries accessed using -l. This makes it possible');
  253. console.log(' to have multiple flavors of Amber and libraries in the same place.');
  254. console.log('');
  255. console.log('');
  256. console.log(' Example invocations:');
  257. console.log('');
  258. console.log(' Just compile Kernel-Objects.st to Kernel-Objects.js:');
  259. console.log('');
  260. console.log(' amberc Kernel-Objects.st');
  261. console.log('');
  262. console.log(' Compile Hello.st to Hello.js and create complete program called Program.js.');
  263. console.log(' Additionally add a call to the class method Hello>>main:');
  264. console.log('');
  265. console.log(' amberc -m Hello Hello.st Program');
  266. console.log('');
  267. console.log(' Compile Cat1.st and Cat2.st files into corresponding .js files.');
  268. console.log(' Link them with myboot.js and myKernel.js and add myinit.js as custom');
  269. console.log(' initializer file. Add main.js last which contains the startup code');
  270. console.log(' and merge everything into a complete program named Program.js:');
  271. console.log('');
  272. console.log(' amberc -M main.js -i myinit.js myboot.js myKernel.js Cat1.st Cat2.st Program');
  273. process.exit();
  274. };
  275. /**
  276. * Checks if the java executable exists and afterwards,
  277. * if compiler.jar exists at the path stored in this.closure_jar.
  278. * All closure related entries are set to false upon failure.
  279. *
  280. * callback gets called in any case.
  281. */
  282. AmberC.prototype.check_for_closure_compiler = function(callback) {
  283. var defaults = this.defaults;
  284. var self = this;
  285. if (defaults.closure) {
  286. exec('which java', function(error, stdout, stderr) {
  287. // stdout contains path to java executable
  288. if (null !== error) {
  289. console.warn('java is not installed but is needed for -O, -A or -o (Closure compiler).');
  290. defaults.closure = false;
  291. defaults.closure_parts = false;
  292. defaults.closure_full = false;
  293. callback();
  294. return;
  295. }
  296. path.exists(self.closure_jar, function(exists) {
  297. if (!exists) {
  298. console.warn('Can not find Closure compiler at: ' + self.closure_jar);
  299. defaults.closure = false;
  300. defaults.closure_parts = false;
  301. defaults.closure_full = false;
  302. callback();
  303. return;
  304. }
  305. });
  306. });
  307. } else {
  308. callback();
  309. }
  310. };
  311. /**
  312. * Check if the file given as parameter exists in the local directory or in $AMBER/js/.
  313. * '.js' is appended first.
  314. *
  315. * @param filename name of a file without '.js' prefix
  316. * @param callback gets called on success with path to .js file as parameter
  317. */
  318. AmberC.prototype.resolve_js = function(filename, callback) {
  319. var jsFile = filename + this.defaults.loadsuffix + '.js';
  320. var amberJsFile = path.join(this.amber_dir, 'js', jsFile);
  321. console.log('Resolving: ' + jsFile);
  322. path.exists(jsFile, function(exists) {
  323. if (exists) {
  324. callback(jsFile);
  325. } else {
  326. path.exists(amberJsFile, function(exists) {
  327. if (exists) {
  328. callback(amberJsFile);
  329. } else {
  330. throw(new Error('JavaScript file not found: ' + jsFile));
  331. }
  332. });
  333. }
  334. });
  335. };
  336. /**
  337. * Collect libraries and Smalltalk files looking
  338. * both locally and in $AMBER/js and $AMBER/st.
  339. * Followed by resolve_libraries().
  340. */
  341. AmberC.prototype.collect_files = function(stFiles, jsFiles) {
  342. var self = this;
  343. var collected_files = new Combo(function() {
  344. self.resolve_libraries();
  345. });
  346. this.collect_st_files(stFiles, collected_files.add());
  347. this.collect_js_files(jsFiles, collected_files.add());
  348. };
  349. /**
  350. * Resolve st files given by stFiles and add them to defaults.compile.
  351. * Respective categories get added to defaults.compile_categories.
  352. * callback is evaluated afterwards.
  353. */
  354. AmberC.prototype.collect_st_files = function(stFiles, callback) {
  355. var defaults = this.defaults;
  356. var self = this;
  357. var collected_st_files = new Combo(function() {
  358. Array.prototype.slice.call(arguments).forEach(function(data) {
  359. if (undefined !== data[0]) {
  360. var stFile = data[0];
  361. var stCategory = data[1];
  362. defaults.compile.push(stFile);
  363. defaults.compiled_categories.push(stCategory);
  364. defaults.compiled.push(stCategory + defaults.suffix_used + '.js');
  365. }
  366. });
  367. callback();
  368. });
  369. stFiles.forEach(function(stFile) {
  370. var _callback = collected_st_files.add();
  371. console.log('Checking: ' + stFile);
  372. var category = path.basename(stFile, '.st');
  373. var amberStFile = path.join(self.amber_dir, 'st', stFile);
  374. path.exists(stFile, function(exists) {
  375. if (exists) {
  376. _callback(stFile, category);
  377. } else {
  378. path.exists(amberJsFile, function(exists) {
  379. if (exists) {
  380. _callback(amberStFile, category);
  381. } else {
  382. throw(new Error('JavaScript file not found: ' + jsFile));
  383. }
  384. });
  385. }
  386. });
  387. });
  388. always_resolve(collected_st_files.add());
  389. };
  390. /**
  391. * Resolve js files given by jsFiles and add them to defaults.libraries.
  392. * callback is evaluated afterwards.
  393. */
  394. AmberC.prototype.collect_js_files = function(jsFiles, callback) {
  395. var self = this;
  396. var collected_js_files = new Combo(function() {
  397. Array.prototype.slice.call(arguments).forEach(function(file) {
  398. if (undefined !== file[0]) {
  399. self.defaults.libraries.push(file[0]);
  400. }
  401. });
  402. callback();
  403. });
  404. jsFiles.forEach(function(jsFile) {
  405. self.resolve_js(currentFile, collected_js_files.add());
  406. });
  407. always_resolve(collected_js_files.add());
  408. };
  409. /**
  410. * Resolve kernel and compiler files.
  411. * Followed by resolve_init().
  412. */
  413. AmberC.prototype.resolve_libraries = function() {
  414. // Resolve libraries listed in this.kernel_libraries
  415. var self = this;
  416. var all_resolved = new Combo(function(resolved_library_files, resolved_compiler_files) {
  417. self.resolve_init(resolved_compiler_files[0]);
  418. });
  419. this.resolve_kernel(all_resolved.add());
  420. this.resolve_compiler(all_resolved.add());
  421. };
  422. /**
  423. * Resolve .js files needed by kernel
  424. * callback is evaluated afterwards.
  425. */
  426. AmberC.prototype.resolve_kernel = function(callback) {
  427. var self = this;
  428. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  429. var kernel_resolved = new Combo(function() {
  430. Array.prototype.slice.call(arguments).forEach(function(file) {
  431. if (undefined !== file[0]) {
  432. self.defaults.libraries.push(file[0]);
  433. }
  434. });
  435. callback(null);
  436. });
  437. kernel_files.forEach(function(file) {
  438. self.resolve_js(file, kernel_resolved.add());
  439. });
  440. always_resolve(kernel_resolved.add());
  441. };
  442. /**
  443. * Resolve .js files needed by compiler.
  444. * callback is evaluated afterwards with resolved files as argument.
  445. */
  446. AmberC.prototype.resolve_compiler = function(callback) {
  447. // Resolve compiler libraries
  448. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  449. var compiler_resolved = new Combo(function() {
  450. var compilerFiles = [];
  451. Array.prototype.slice.call(arguments).forEach(function(file) {
  452. if (undefined !== file[0]) {
  453. compilerFiles.push(file[0]);
  454. }
  455. });
  456. callback(compilerFiles);
  457. });
  458. var self = this
  459. compiler_files.forEach(function(file) {
  460. self.resolve_js(file, compiler_resolved.add());
  461. });
  462. always_resolve(compiler_resolved.add());
  463. };
  464. /**
  465. * Resolves default.init and adds it to compilerFiles.
  466. * Followed by create_compiler().
  467. */
  468. AmberC.prototype.resolve_init = function(compilerFiles) {
  469. // check and add init.js
  470. var initFile = this.defaults.init;
  471. if ('.js' !== path.extname(initFile)) {
  472. initFile = this.resolve_js(initFile);
  473. this.defaults.init = initFile;
  474. }
  475. compilerFiles.push(initFile);
  476. this.create_compiler(compilerFiles);
  477. };
  478. /**
  479. * Read all .js files needed by compiler and eval() them.
  480. * The finished Compiler gets stored in defaults.smalltalk.
  481. * Followed by compile().
  482. */
  483. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  484. var self = this;
  485. var compiler_files = new Combo(function() {
  486. var content = '(function() {';
  487. Array.prototype.slice.call(arguments).forEach(function(data) {
  488. // data is an array where index 0 is the error code and index 1 contains the data
  489. content += data[1];
  490. });
  491. content = content + 'return smalltalk;})();';
  492. self.defaults.smalltalk = eval(content);
  493. console.log('Compiler loaded');
  494. self.compile();
  495. });
  496. compilerFilesArray.forEach(function(file) {
  497. console.log('Loading file: ' + file);
  498. fs.readFile(file, compiler_files.add());
  499. });
  500. };
  501. /**
  502. * Compile all given .st files by importing them.
  503. * Followed by category_export().
  504. */
  505. AmberC.prototype.compile = function() {
  506. console.log('Compiling collected .st files')
  507. // import .st files
  508. var self = this;
  509. var imports = new Combo(function() {
  510. Array.prototype.slice.call(arguments).forEach(function(code) {
  511. // get element 0 of code since all return values are stored inside an array by Combo
  512. self.defaults.smalltalk.Importer._new()._import_(code[0]._stream());
  513. });
  514. self.category_export();
  515. });
  516. this.defaults.compile.forEach(function(stFile) {
  517. var callback = imports.add();
  518. if (/\.st/.test(stFile)) {
  519. console.log('Importing: ' + stFile);
  520. fs.readFile(stFile, 'utf8', function(err, data) {
  521. if (!err)
  522. callback(data);
  523. else
  524. throw new Error('Could not import: ' + stFile);
  525. });
  526. }
  527. });
  528. };
  529. /**
  530. * Export compiled categories to JavaScript files.
  531. * Followed by verify().
  532. */
  533. AmberC.prototype.category_export = function() {
  534. var defaults = this.defaults;
  535. var self = this;
  536. // export categories as .js
  537. map(defaults.compiled_categories, function(category, callback) {
  538. var jsFile = category + defaults.suffix_used + '.js';
  539. var jsFileDeploy = category + defaults.suffix_used + '.deploy.js';
  540. console.log('Exporting ' + (defaults.deploy ? '(debug + deploy)' : '(debug)')
  541. + ' category ' + category + ' as ' + jsFile
  542. + (defaults.deploy ? ' and ' + jsFileDeploy : ''));
  543. fs.writeFile(jsFile, defaults.smalltalk.Exporter._new()._exportPackage_(category), function(err) {
  544. if (defaults.deploy) {
  545. fs.writeFile(jsFileDeploy, defaults.smalltalk.StrippedExporter._new()._exportPackage_(category), callback);
  546. } else {
  547. callback(null, null);
  548. }
  549. });
  550. }, function(err, result){
  551. self.verify();
  552. });
  553. };
  554. /**
  555. * Verify if all .st files have been compiled.
  556. * Followed by compose_js_files() and optimize().
  557. */
  558. AmberC.prototype.verify = function() {
  559. console.log('Verifying if all .st files were compiled');
  560. var self = this;
  561. map(this.defaults.compiled, function(file, callback) {
  562. path.exists(file, function(exists) {
  563. if (exists)
  564. callback(null, null);
  565. else
  566. throw(new Error('Compilation failed of: ' + file));
  567. });
  568. }, function(err, result) {
  569. self.compose_js_files();
  570. self.optimize();
  571. });
  572. };
  573. /**
  574. * Synchronous function.
  575. * Concatenates compiled JavaScript files into one file in the correct order.
  576. * The name of the produced file is given by defaults.program (set by the last commandline option).
  577. */
  578. AmberC.prototype.compose_js_files = function() {
  579. var defaults = this.defaults;
  580. if (undefined !== defaults.program) {
  581. return;
  582. }
  583. var program_files = [];
  584. if (undefined !== defaults.libraries) {
  585. console.log('Collecting libraries: ' + defaults.libraries);
  586. program_files.push.apply(program_files, defaults.libraries);
  587. }
  588. if (undefined !== defaults.compiled) {
  589. console.log('Collecting compiled files: ' + defaults.compiled);
  590. program_files.push.apply(program_files, defaults.compiled);
  591. }
  592. if (undefined !== defaults.init) {
  593. console.log('Adding initializer ' + defaults.init);
  594. program_files.push(defaults.init);
  595. }
  596. console.log('Writing program file: %s.js', defaults.program);
  597. var fileStream = fs.createWriteStream(defaults.program + '.js');
  598. fileStream.on('error', function(error) {
  599. console.log(error);
  600. });
  601. program_files.forEach(function(file) {
  602. console.log('Checking : ' + file);
  603. if(path.existsSync(file)) {
  604. fileStream.write(fs.readFileSync(file));
  605. } else {
  606. throw(new Error('Can not find file ' + file));
  607. }
  608. });
  609. if (undefined !== defaults.main) {
  610. console.log('Adding call to: %s>>main', defaults.main);
  611. fileStream.write('smalltalk.' + defaults.main + '._main()');
  612. }
  613. if (undefined !== defaults.mainfile && path.existsSync(defaults.mainfile)) {
  614. console.log('Adding main file: ' + defaults.mainfile);
  615. fileStream.write(fs.readFileSync(defaults.mainfile));
  616. }
  617. fileStream.end();
  618. console.log('Done.');
  619. };
  620. /**
  621. * Optimize created JavaScript files with Google Closure compiler depending
  622. * on the flags: defaults.closure_parts, defaults.closure_full.
  623. */
  624. AmberC.prototype.optimize = function() {
  625. var defaults = this.defaults;
  626. var self = this;
  627. var optimization_done = new Combo(function() {
  628. console.timeEnd('Compile Time');
  629. });
  630. if (defaults.closure_parts) {
  631. console.log('Compiling all js files using Google closure compiler.');
  632. var allJsFiles = defaults.compiled.concat(defaults.libraries);
  633. allJsFiles.forEach(function(file) {
  634. var minifiedName = path.basename(file, '.js') + '.min.js';
  635. self.closure_compile(file, minifiedName, optimization_done.add());
  636. });
  637. }
  638. if (defaults.closure_full) {
  639. console.log('Compiling ' + defaults.program + '.js file using Google closure compiler.');
  640. self.closure_compile(defaults.program + '.js', defaults.program + '.min.js', optimization_done.add());
  641. }
  642. always_resolve(optimization_done.add());
  643. };
  644. /**
  645. * Compile sourceFile into minifiedFile with Google Closure compiler.
  646. * callback gets executed once finished.
  647. */
  648. AmberC.prototype.closure_compile = function(sourceFile, minifiedFile, callback) {
  649. // exec is asynchronous
  650. var self = this;
  651. exec(
  652. 'java -jar ' +
  653. self.closure_jar + ' ' +
  654. self.defaults.closure_options +
  655. ' --js '+ sourceFile +
  656. ' --js_output_file '+ minifiedFile,
  657. function (error, stdout, stderr) {
  658. if (error) {
  659. console.log(stderr);
  660. } else {
  661. console.log(stdout);
  662. console.log('Minified: '+ minifiedFile);
  663. }
  664. callback();
  665. }
  666. );
  667. };
  668. module.exports.Compiler = AmberC;