amberc.js 22 KB

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