1
0

amberc.js 21 KB

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