2
0

amberc.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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': '',
  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. callback();
  311. return;
  312. }
  313. });
  314. });
  315. } else {
  316. callback();
  317. }
  318. };
  319. /**
  320. * Check if the file given as parameter exists in the local directory or in $AMBER/js/.
  321. * '.js' is appended first.
  322. *
  323. * @param filename name of a file without '.js' prefix
  324. * @param callback gets called on success with path to .js file as parameter
  325. */
  326. AmberC.prototype.resolve_js = function(filename, callback) {
  327. var baseName = path.basename(filename, '.js');
  328. var jsFile = baseName + this.defaults.loadsuffix + '.js';
  329. var amberJsFile = path.join(this.amber_dir, 'js', jsFile);
  330. console.log('Resolving: ' + jsFile);
  331. path.exists(jsFile, function(exists) {
  332. if (exists) {
  333. callback(jsFile);
  334. } else {
  335. path.exists(amberJsFile, function(exists) {
  336. if (exists) {
  337. callback(amberJsFile);
  338. } else {
  339. throw(new Error('JavaScript file not found: ' + jsFile));
  340. }
  341. });
  342. }
  343. });
  344. };
  345. /**
  346. * Collect libraries and Smalltalk files looking
  347. * both locally and in $AMBER/js and $AMBER/st.
  348. * Followed by resolve_libraries().
  349. */
  350. AmberC.prototype.collect_files = function(stFiles, jsFiles) {
  351. var self = this;
  352. var collected_files = new Combo(function() {
  353. self.resolve_libraries();
  354. });
  355. if (0 !== stFiles.length) {
  356. self.collect_st_files(stFiles, collected_files.add());
  357. }
  358. if (0 !== jsFiles.length) {
  359. self.collect_js_files(jsFiles, collected_files.add());
  360. }
  361. };
  362. /**
  363. * Resolve st files given by stFiles and add them to defaults.compile.
  364. * Respective categories get added to defaults.compile_categories.
  365. * callback is evaluated afterwards.
  366. */
  367. AmberC.prototype.collect_st_files = function(stFiles, callback) {
  368. var defaults = this.defaults;
  369. var self = this;
  370. var collected_st_files = new Combo(function() {
  371. Array.prototype.slice.call(arguments).forEach(function(data) {
  372. var stFile = data[0];
  373. var stCategory = data[1];
  374. defaults.compile.push(stFile);
  375. defaults.compiled_categories.push(stCategory);
  376. defaults.compiled.push(stCategory + defaults.suffix_used + '.js');
  377. });
  378. callback();
  379. });
  380. stFiles.forEach(function(stFile) {
  381. var _callback = collected_st_files.add();
  382. console.log('Checking: ' + stFile);
  383. var category = path.basename(stFile, '.st');
  384. var amberStFile = path.join(self.amber_dir, 'st', stFile);
  385. path.exists(stFile, function(exists) {
  386. if (exists) {
  387. _callback(stFile, category);
  388. } else {
  389. path.exists(amberStFile, function(exists) {
  390. if (exists) {
  391. _callback(amberStFile, category);
  392. } else {
  393. throw(new Error('Smalltalk file not found: ' + amberStFile));
  394. }
  395. });
  396. }
  397. });
  398. });
  399. };
  400. /**
  401. * Resolve js files given by jsFiles and add them to defaults.libraries.
  402. * callback is evaluated afterwards.
  403. */
  404. AmberC.prototype.collect_js_files = function(jsFiles, callback) {
  405. var self = this;
  406. var collected_js_files = new Combo(function() {
  407. Array.prototype.slice.call(arguments).forEach(function(file) {
  408. self.defaults.libraries.push(file[0]);
  409. });
  410. callback();
  411. });
  412. jsFiles.forEach(function(jsFile) {
  413. self.resolve_js(jsFile, collected_js_files.add());
  414. });
  415. };
  416. /**
  417. * Resolve kernel and compiler files.
  418. * Followed by resolve_init().
  419. */
  420. AmberC.prototype.resolve_libraries = function() {
  421. // Resolve libraries listed in this.kernel_libraries
  422. var self = this;
  423. var all_resolved = new Combo(function(resolved_library_files, resolved_compiler_files) {
  424. self.resolve_init(resolved_compiler_files[0]);
  425. });
  426. this.resolve_kernel(all_resolved.add());
  427. this.resolve_compiler(all_resolved.add());
  428. };
  429. /**
  430. * Resolve .js files needed by kernel
  431. * callback is evaluated afterwards.
  432. */
  433. AmberC.prototype.resolve_kernel = function(callback) {
  434. var self = this;
  435. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  436. var kernel_resolved = new Combo(function() {
  437. Array.prototype.slice.call(arguments).forEach(function(file) {
  438. if (undefined !== file[0]) {
  439. self.defaults.libraries.push(file[0]);
  440. }
  441. });
  442. callback(null);
  443. });
  444. kernel_files.forEach(function(file) {
  445. self.resolve_js(file, kernel_resolved.add());
  446. });
  447. always_resolve(kernel_resolved.add());
  448. };
  449. /**
  450. * Resolve .js files needed by compiler.
  451. * callback is evaluated afterwards with resolved files as argument.
  452. */
  453. AmberC.prototype.resolve_compiler = function(callback) {
  454. // Resolve compiler libraries
  455. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  456. var compiler_resolved = new Combo(function() {
  457. var compilerFiles = [];
  458. Array.prototype.slice.call(arguments).forEach(function(file) {
  459. if (undefined !== file[0]) {
  460. compilerFiles.push(file[0]);
  461. }
  462. });
  463. callback(compilerFiles);
  464. });
  465. var self = this
  466. compiler_files.forEach(function(file) {
  467. self.resolve_js(file, compiler_resolved.add());
  468. });
  469. always_resolve(compiler_resolved.add());
  470. };
  471. /**
  472. * Resolves default.init and adds it to compilerFiles.
  473. * Followed by create_compiler().
  474. */
  475. AmberC.prototype.resolve_init = function(compilerFiles) {
  476. // check and add init.js
  477. var initFile = this.defaults.init;
  478. if ('.js' !== path.extname(initFile)) {
  479. initFile = this.resolve_js(initFile);
  480. this.defaults.init = initFile;
  481. }
  482. compilerFiles.push(initFile);
  483. this.create_compiler(compilerFiles);
  484. };
  485. /**
  486. * Read all .js files needed by compiler and eval() them.
  487. * The finished Compiler gets stored in defaults.smalltalk.
  488. * Followed by compile().
  489. */
  490. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  491. var self = this;
  492. var compiler_files = new Combo(function() {
  493. var content = '(function() {';
  494. Array.prototype.slice.call(arguments).forEach(function(data) {
  495. // data is an array where index 0 is the error code and index 1 contains the data
  496. content += data[1];
  497. });
  498. content = content + 'return smalltalk;})();';
  499. self.defaults.smalltalk = eval(content);
  500. console.log('Compiler loaded');
  501. self.compile();
  502. });
  503. compilerFilesArray.forEach(function(file) {
  504. console.log('Loading file: ' + file);
  505. fs.readFile(file, compiler_files.add());
  506. });
  507. };
  508. /**
  509. * Compile all given .st files by importing them.
  510. * Followed by category_export().
  511. */
  512. AmberC.prototype.compile = function() {
  513. console.log('Compiling collected .st files')
  514. // import .st files
  515. var self = this;
  516. var imports = new Combo(function() {
  517. Array.prototype.slice.call(arguments).forEach(function(code) {
  518. if (undefined !== code[0]) {
  519. // get element 0 of code since all return values are stored inside an array by Combo
  520. self.defaults.smalltalk.Importer._new()._import_(code[0]._stream());
  521. }
  522. });
  523. self.category_export();
  524. });
  525. this.defaults.compile.forEach(function(stFile) {
  526. var callback = imports.add();
  527. if (/\.st/.test(stFile)) {
  528. console.log('Importing: ' + stFile);
  529. fs.readFile(stFile, 'utf8', function(err, data) {
  530. if (!err)
  531. callback(data);
  532. else
  533. throw new Error('Could not import: ' + stFile);
  534. });
  535. }
  536. });
  537. always_resolve(imports.add());
  538. };
  539. /**
  540. * Export compiled categories to JavaScript files.
  541. * Followed by verify().
  542. */
  543. AmberC.prototype.category_export = function() {
  544. var defaults = this.defaults;
  545. var self = this;
  546. // export categories as .js
  547. async_map(defaults.compiled_categories, function(category, callback) {
  548. var jsFile = category + defaults.suffix_used + '.js';
  549. var jsFileDeploy = category + defaults.suffix_used + '.deploy.js';
  550. console.log('Exporting ' + (defaults.deploy ? '(debug + deploy)' : '(debug)')
  551. + ' category ' + category + ' as ' + jsFile
  552. + (defaults.deploy ? ' and ' + jsFileDeploy : ''));
  553. fs.writeFile(jsFile, defaults.smalltalk.Exporter._new()._exportPackage_(category), function(err) {
  554. if (defaults.deploy) {
  555. fs.writeFile(jsFileDeploy, defaults.smalltalk.StrippedExporter._new()._exportPackage_(category), callback);
  556. } else {
  557. callback(null, null);
  558. }
  559. });
  560. }, function(err, result){
  561. self.verify();
  562. });
  563. };
  564. /**
  565. * Verify if all .st files have been compiled.
  566. * Followed by compose_js_files() and optimize().
  567. */
  568. AmberC.prototype.verify = function() {
  569. console.log('Verifying if all .st files were compiled');
  570. var self = this;
  571. async_map(this.defaults.compiled, function(file, callback) {
  572. path.exists(file, function(exists) {
  573. if (exists)
  574. callback(null, null);
  575. else
  576. throw(new Error('Compilation failed of: ' + file));
  577. });
  578. }, function(err, result) {
  579. self.compose_js_files();
  580. });
  581. };
  582. /**
  583. * Synchronous function.
  584. * Concatenates compiled JavaScript files into one file in the correct order.
  585. * The name of the produced file is given by defaults.program (set by the last commandline option).
  586. */
  587. AmberC.prototype.compose_js_files = function() {
  588. var defaults = this.defaults;
  589. if (undefined === defaults.program) {
  590. return;
  591. }
  592. var program_files = [];
  593. if (0 !== defaults.libraries.length) {
  594. console.log('Collecting libraries: ' + defaults.libraries);
  595. program_files.push.apply(program_files, defaults.libraries);
  596. }
  597. if (0 !== defaults.compiled.length) {
  598. console.log('Collecting compiled files: ' + defaults.compiled);
  599. program_files.push.apply(program_files, defaults.compiled);
  600. }
  601. if (undefined !== defaults.init) {
  602. console.log('Adding initializer ' + defaults.init);
  603. program_files.push(defaults.init);
  604. }
  605. console.log('Writing program file: %s.js', defaults.program);
  606. var fileStream = fs.createWriteStream(defaults.program + defaults.suffix_used + '.js');
  607. fileStream.on('error', function(error) {
  608. fileStream.end();
  609. console.log(error);
  610. });
  611. var self = this;
  612. fileStream.on('close', function(){
  613. self.optimize();
  614. });
  615. program_files.forEach(function(file) {
  616. if(path.existsSync(file)) {
  617. console.log('Adding : ' + file);
  618. console.log(fileStream.write(fs.readFileSync(file)));
  619. } else {
  620. fileStream.end();
  621. throw(new Error('Can not find file ' + file));
  622. }
  623. });
  624. if (undefined !== defaults.main) {
  625. console.log('Adding call to: %s>>main', defaults.main);
  626. fileStream.write('smalltalk.' + defaults.main + '._main()');
  627. }
  628. if (undefined !== defaults.mainfile && path.existsSync(defaults.mainfile)) {
  629. console.log('Adding main file: ' + defaults.mainfile);
  630. fileStream.write(fs.readFileSync(defaults.mainfile));
  631. }
  632. console.log('Done.');
  633. fileStream.end();
  634. };
  635. /**
  636. * Optimize created JavaScript files with Google Closure compiler depending
  637. * on the flags: defaults.closure_parts, defaults.closure_full.
  638. */
  639. AmberC.prototype.optimize = function() {
  640. var defaults = this.defaults;
  641. var self = this;
  642. var optimization_done = new Combo(function() {
  643. console.timeEnd('Compile Time');
  644. if (undefined !== defaults.finished_callback) {
  645. defaults.finished_callback();
  646. }
  647. });
  648. if (defaults.closure_parts) {
  649. console.log('Compiling all js files using Google closure compiler.');
  650. var allJsFiles = defaults.compiled.concat(defaults.libraries);
  651. allJsFiles.forEach(function(file) {
  652. var minifiedName = path.basename(file, '.js') + '.min.js';
  653. self.closure_compile(file, minifiedName, optimization_done.add());
  654. });
  655. }
  656. if (defaults.closure_full) {
  657. console.log('Compiling ' + defaults.program + '.js file using Google closure compiler.');
  658. self.closure_compile(defaults.program + '.js', defaults.program + '.min.js', optimization_done.add());
  659. }
  660. always_resolve(optimization_done.add());
  661. };
  662. /**
  663. * Compile sourceFile into minifiedFile with Google Closure compiler.
  664. * callback gets executed once finished.
  665. */
  666. AmberC.prototype.closure_compile = function(sourceFile, minifiedFile, callback) {
  667. // exec is asynchronous
  668. var self = this;
  669. exec(
  670. 'java -jar ' +
  671. self.closure_jar + ' ' +
  672. self.defaults.closure_options +
  673. ' --js '+ sourceFile +
  674. ' --js_output_file '+ minifiedFile,
  675. function (error, stdout, stderr) {
  676. if (error) {
  677. console.log(stderr);
  678. } else {
  679. console.log(stdout);
  680. console.log('Minified: '+ minifiedFile);
  681. }
  682. callback();
  683. }
  684. );
  685. };
  686. module.exports.Compiler = AmberC;
  687. module.exports.Combo = Combo;
  688. module.exports.map = async_map;