1
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. * Helper for concatenating Amber generated AMD modules.
  42. * The produced output can be exported and run as an independent program.
  43. *
  44. * var concatenator = createConcatenator();
  45. * concatenator.start(); // write the required AMD define header
  46. * concatenator.add(module1);
  47. * concatenator.addId(module1_ID);
  48. * //...
  49. * concatenator.finish("//some last code");
  50. * var concatenation = concatenator.toString();
  51. * // The variable concatenation contains the concatenated result
  52. * // which can either be stored in a file or interpreted with eval().
  53. */
  54. function createConcatenator () {
  55. var defineAmdDefine = function () {
  56. var path = require('path');
  57. return ($AMDEFINE_SRC$)(module);
  58. };
  59. // The createAmdefineString is hack to help injecting amdefine into the concatenated output.
  60. //
  61. // Usually, the line 'var define = require('amdefine')(module), requirejs = define.require;'
  62. // is needed when using amdefine with node and npm installed.
  63. // var f = require('amdefine') itself returns one big self-sufficient function which must be called
  64. // as f(module) to get the define you can use.
  65. //
  66. // However, amdefine needs the definition of the 'path' variable (node's internal 'path' module).
  67. // To create this dependency the defineAmdDefine() function is used which defines
  68. // the path variable first and adds a placeholder for the amdefine function/sourcecode.
  69. // The defineAmdDefine() function is then converted to its string representation
  70. // and the placeholder is replaced with the actual sourcecode of the amdefine function.
  71. var createAmdefineString = function() {
  72. return ('' + defineAmdDefine).replace('$AMDEFINE_SRC$', '' + require('amdefine'));
  73. }
  74. return {
  75. elements: [],
  76. ids: [],
  77. add: function () {
  78. this.elements.push.apply(this.elements, arguments);
  79. },
  80. addId: function () {
  81. this.ids.push.apply(this.ids, arguments);
  82. },
  83. forEach: function () {
  84. this.elements.forEach.apply(this.elements, arguments);
  85. },
  86. start: function () {
  87. this.add(
  88. 'var define = (' + createAmdefineString() + ')(), requirejs = define.require;',
  89. 'define("amber_vm/browser-compatibility", [], {});'
  90. );
  91. },
  92. finish: function (realWork) {
  93. this.add(
  94. 'define("amber_vm/_init", ["amber_vm/smalltalk","' + this.ids.join('","') + '"], function (smalltalk) {',
  95. 'smalltalk.initialize();',
  96. realWork,
  97. '});', 'requirejs("amber_vm/_init");'
  98. );
  99. },
  100. toString: function () {
  101. return this.elements.join('\n');
  102. }
  103. };
  104. }
  105. /**
  106. * Combine several async functions and evaluate callback once all of them have finished.
  107. * Taken from: http://howtonode.org/control-flow
  108. */
  109. function Combo(callback) {
  110. this.callback = callback;
  111. this.items = 0;
  112. this.results = [];
  113. }
  114. Combo.prototype = {
  115. add: function () {
  116. var self = this,
  117. id = this.items;
  118. this.items++;
  119. return function () {
  120. self.check(id, arguments);
  121. };
  122. },
  123. check: function (id, arguments) {
  124. this.results[id] = Array.prototype.slice.call(arguments);
  125. this.items--;
  126. if (this.items == 0) {
  127. this.callback.apply(this, this.results);
  128. }
  129. }
  130. };
  131. var path = require('path'),
  132. util = require('util'),
  133. fs = require('fs'),
  134. exec = require('child_process').exec;
  135. /**
  136. * AmberC constructor function.
  137. * amber_dir: points to the location of an amber installation
  138. * closure_jar: location of compiler.jar (can be left undefined)
  139. */
  140. function AmberC(amber_dir, closure_jar) {
  141. this.amber_dir = amber_dir;
  142. this.closure_jar = closure_jar || '';
  143. this.kernel_libraries = ['boot', '@smalltalk', '@nil', '@_st', 'Kernel-Objects', 'Kernel-Classes', 'Kernel-Methods',
  144. 'Kernel-Collections', 'Kernel-Exceptions', 'Kernel-Transcript',
  145. 'Kernel-Announcements'];
  146. this.compiler_libraries = this.kernel_libraries.concat(['parser', 'Importer-Exporter',
  147. 'Compiler-Core', 'Compiler-AST', 'Compiler-Exceptions', 'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic']);
  148. }
  149. /**
  150. * Default values.
  151. */
  152. var createDefaults = function(amber_dir, finished_callback){
  153. if (undefined === amber_dir) {
  154. throw new Error('createDefaults() function needs a valid amber_dir parameter');
  155. }
  156. return {
  157. 'load': [],
  158. 'main': undefined,
  159. 'mainfile': undefined,
  160. 'stFiles': [],
  161. 'jsFiles': [],
  162. 'jsGlobals': [],
  163. 'closure': false,
  164. 'closure_parts': false,
  165. 'closure_full': false,
  166. 'closure_options': ' --language_in=ECMASCRIPT5 ',
  167. 'suffix': '',
  168. 'loadsuffix': '',
  169. 'suffix_used': '',
  170. 'deploy': false,
  171. 'libraries': [],
  172. 'compile': [],
  173. 'compiled': [],
  174. 'program': undefined,
  175. 'output_dir': undefined,
  176. 'verbose': false,
  177. 'finished_callback': finished_callback
  178. };
  179. };
  180. /**
  181. * Main function for executing the compiler.
  182. * If check_configuration_ok() returns successfully the configuration is set on the current compiler
  183. * instance and check_for_closure_compiler() gets called.
  184. * The last step is to call collect_files().
  185. */
  186. AmberC.prototype.main = function(configuration, finished_callback) {
  187. console.time('Compile Time');
  188. if (undefined !== finished_callback) {
  189. configuration.finished_callback = finished_callback;
  190. }
  191. if (configuration.closure || configuration.closure_parts || configuration.closure_full) {
  192. configuration.deploy = true;
  193. }
  194. console.ambercLog = console.log;
  195. if (false === configuration.verbose) {
  196. console.log = function() {};
  197. }
  198. if (this.check_configuration_ok(configuration)) {
  199. this.defaults = configuration;
  200. this.defaults.smalltalk = {}; // the evaluated compiler will be stored in this variable (see create_compiler)
  201. var self = this;
  202. this.check_for_closure_compiler(function(){
  203. self.collect_files(self.defaults.stFiles, self.defaults.jsFiles)
  204. });
  205. }
  206. };
  207. /**
  208. * Check if the passed in configuration object has sufficient/nonconflicting values
  209. */
  210. AmberC.prototype.check_configuration_ok = function(configuration) {
  211. if (undefined === configuration) {
  212. throw new Error('AmberC.check_configuration_ok(): missing configuration object');
  213. }
  214. if (0 === configuration.jsFiles.length && 0 === configuration.stFiles.lenght) {
  215. throw new Error('AmberC.check_configuration_ok(): no files to compile/link specified in configuration object');
  216. }
  217. return true;
  218. };
  219. /**
  220. * Checks if the java executable exists and afterwards,
  221. * if compiler.jar exists at the path stored in this.closure_jar.
  222. * All closure related entries are set to false upon failure.
  223. *
  224. * callback gets called in any case.
  225. */
  226. AmberC.prototype.check_for_closure_compiler = function(callback) {
  227. var defaults = this.defaults;
  228. var self = this;
  229. if (defaults.closure) {
  230. exec('which java', function(error, stdout, stderr) {
  231. // stdout contains path to java executable
  232. if (null !== error) {
  233. console.warn('java is not installed but is needed for running the Closure compiler (-O, -A or -o flags).');
  234. defaults.closure = false;
  235. defaults.closure_parts = false;
  236. defaults.closure_full = false;
  237. callback();
  238. return;
  239. }
  240. fs.exists(self.closure_jar, function(exists) {
  241. if (!exists) {
  242. console.warn('Can not find Closure compiler at: ' + self.closure_jar);
  243. defaults.closure = false;
  244. defaults.closure_parts = false;
  245. defaults.closure_full = false;
  246. } else {
  247. console.warn('Closure compiler found at: ' + self.closure_jar);
  248. }
  249. callback();
  250. return;
  251. });
  252. });
  253. } else {
  254. callback();
  255. }
  256. };
  257. /**
  258. * Check if the file given as parameter exists in the local directory or in $AMBER/js/.
  259. * '.js' is appended first.
  260. *
  261. * @param filename name of a file without '.js' prefix
  262. * @param callback gets called on success with path to .js file as parameter
  263. */
  264. AmberC.prototype.resolve_js = function(filename, callback) {
  265. var special = filename[0] == "@";
  266. if (special) {
  267. filename = filename.slice(1);
  268. }
  269. var baseName = path.basename(filename, '.js');
  270. var jsFile = baseName + this.defaults.loadsuffix + '.js';
  271. var amberJsFile = path.join(this.amber_dir, (special ? 'js/lib' : 'js'), jsFile);
  272. console.log('Resolving: ' + jsFile);
  273. fs.exists(jsFile, function(exists) {
  274. if (exists) {
  275. callback(jsFile);
  276. } else {
  277. fs.exists(amberJsFile, function(exists) {
  278. if (exists) {
  279. callback(amberJsFile);
  280. } else {
  281. throw(new Error('JavaScript file not found: ' + jsFile));
  282. }
  283. });
  284. }
  285. });
  286. };
  287. /**
  288. * Collect libraries and Smalltalk files looking
  289. * both locally and in $AMBER/js and $AMBER/st.
  290. * Followed by resolve_libraries().
  291. */
  292. AmberC.prototype.collect_files = function(stFiles, jsFiles) {
  293. var self = this;
  294. var collected_files = new Combo(function() {
  295. self.resolve_libraries();
  296. });
  297. if (0 !== stFiles.length) {
  298. self.collect_st_files(stFiles, collected_files.add());
  299. }
  300. if (0 !== jsFiles.length) {
  301. self.collect_js_files(jsFiles, collected_files.add());
  302. }
  303. };
  304. /**
  305. * Resolve st files given by stFiles and add them to defaults.compile.
  306. * Respective categories get added to defaults.compile_categories.
  307. * callback is evaluated afterwards.
  308. */
  309. AmberC.prototype.collect_st_files = function(stFiles, callback) {
  310. var defaults = this.defaults;
  311. var self = this;
  312. var collected_st_files = new Combo(function() {
  313. Array.prototype.slice.call(arguments).forEach(function(data) {
  314. var stFile = data[0];
  315. defaults.compile.push(stFile);
  316. });
  317. callback();
  318. });
  319. stFiles.forEach(function(stFile) {
  320. var _callback = collected_st_files.add();
  321. console.log('Checking: ' + stFile);
  322. var amberStFile = path.join(self.amber_dir, 'st', stFile);
  323. fs.exists(stFile, function(exists) {
  324. if (exists) {
  325. _callback(stFile);
  326. } else {
  327. console.log('Checking: ' + amberStFile);
  328. fs.exists(amberStFile, function(exists) {
  329. if (exists) {
  330. _callback(amberStFile);
  331. } else {
  332. throw(new Error('Smalltalk file not found: ' + amberStFile));
  333. }
  334. });
  335. }
  336. });
  337. });
  338. };
  339. /**
  340. * Resolve js files given by jsFiles and add them to defaults.libraries.
  341. * callback is evaluated afterwards.
  342. */
  343. AmberC.prototype.collect_js_files = function(jsFiles, callback) {
  344. var self = this;
  345. var collected_js_files = new Combo(function() {
  346. Array.prototype.slice.call(arguments).forEach(function(file) {
  347. self.defaults.libraries.push(file[0]);
  348. });
  349. callback();
  350. });
  351. jsFiles.forEach(function(jsFile) {
  352. self.resolve_js(jsFile, collected_js_files.add());
  353. });
  354. };
  355. /**
  356. * Resolve kernel and compiler files.
  357. * Followed by resolve_init().
  358. */
  359. AmberC.prototype.resolve_libraries = function() {
  360. // Resolve libraries listed in this.kernel_libraries
  361. var self = this;
  362. var all_resolved = new Combo(function(resolved_kernel_files, resolved_compiler_files) {
  363. self.create_compiler(resolved_compiler_files[0]);
  364. });
  365. this.resolve_kernel(all_resolved.add());
  366. this.resolve_compiler(all_resolved.add());
  367. };
  368. /**
  369. * Resolve .js files needed by kernel
  370. * callback is evaluated afterwards.
  371. */
  372. AmberC.prototype.resolve_kernel = function(callback) {
  373. var self = this;
  374. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  375. var kernel_resolved = new Combo(function() {
  376. var foundLibraries = [];
  377. Array.prototype.slice.call(arguments).forEach(function(file) {
  378. if (undefined !== file[0]) {
  379. foundLibraries.push(file[0]);
  380. }
  381. });
  382. // boot.js and Kernel files need to be used first
  383. // otherwise the global smalltalk object is undefined
  384. self.defaults.libraries = foundLibraries.concat(self.defaults.libraries);
  385. callback(null);
  386. });
  387. kernel_files.forEach(function(file) {
  388. self.resolve_js(file, kernel_resolved.add());
  389. });
  390. always_resolve(kernel_resolved.add());
  391. };
  392. /**
  393. * Resolve .js files needed by compiler.
  394. * callback is evaluated afterwards with resolved files as argument.
  395. */
  396. AmberC.prototype.resolve_compiler = function(callback) {
  397. // Resolve compiler libraries
  398. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  399. var compiler_resolved = new Combo(function() {
  400. var compilerFiles = [];
  401. Array.prototype.slice.call(arguments).forEach(function(file) {
  402. if (undefined !== file[0]) {
  403. compilerFiles.push(file[0]);
  404. }
  405. });
  406. callback(compilerFiles);
  407. });
  408. var self = this
  409. compiler_files.forEach(function(file) {
  410. self.resolve_js(file, compiler_resolved.add());
  411. });
  412. always_resolve(compiler_resolved.add());
  413. };
  414. /**
  415. * Read all .js files needed by compiler and eval() them.
  416. * The finished Compiler gets stored in defaults.smalltalk.
  417. * Followed by compile().
  418. */
  419. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  420. var self = this;
  421. var compiler_files = new Combo(function() {
  422. var builder = createConcatenator();
  423. builder.add('(function() {');
  424. builder.start();
  425. Array.prototype.slice.call(arguments).forEach(function(data) {
  426. // data is an array where index 0 is the error code and index 1 contains the data
  427. builder.add(data[1]);
  428. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  429. var match = ('' + data[1]).match(/^define\("([^"]*)"/);
  430. if (match) {
  431. builder.addId(match[1]);
  432. }
  433. });
  434. // store the generated smalltalk env in self.defaults.smalltalk
  435. builder.finish('self.defaults.smalltalk = smalltalk;');
  436. builder.add('})();');
  437. eval(builder.toString());
  438. console.log('Compiler loaded');
  439. self.defaults.smalltalk.ErrorHandler._setCurrent_(self.defaults.smalltalk.RethrowErrorHandler._new());
  440. if(0 != self.defaults.jsGlobals.length) {
  441. var jsGlobalVariables = self.defaults.smalltalk.globalJsVariables;
  442. jsGlobalVariables.push.apply(jsGlobalVariables, self.defaults.jsGlobals);
  443. }
  444. self.compile();
  445. });
  446. compilerFilesArray.forEach(function(file) {
  447. console.log('Loading file: ' + file);
  448. fs.readFile(file, compiler_files.add());
  449. });
  450. };
  451. /**
  452. * Compile all given .st files by importing them.
  453. * Followed by category_export().
  454. */
  455. AmberC.prototype.compile = function() {
  456. console.log('Compiling collected .st files')
  457. // import .st files
  458. var self = this;
  459. var imports = new Combo(function() {
  460. Array.prototype.slice.call(arguments).forEach(function(code) {
  461. if (undefined !== code[0]) {
  462. // get element 0 of code since all return values are stored inside an array by Combo
  463. self.defaults.smalltalk.Importer._new()._import_(code[0]._stream());
  464. }
  465. });
  466. self.category_export();
  467. });
  468. this.defaults.compile.forEach(function(stFile) {
  469. var callback = imports.add();
  470. if (/\.st/.test(stFile)) {
  471. console.ambercLog('Importing: ' + stFile);
  472. fs.readFile(stFile, 'utf8', function(err, data) {
  473. if (!err)
  474. callback(data);
  475. else
  476. throw new Error('Could not import: ' + stFile);
  477. });
  478. }
  479. });
  480. always_resolve(imports.add());
  481. };
  482. /**
  483. * Export compiled categories to JavaScript files.
  484. * Followed by verify().
  485. */
  486. AmberC.prototype.category_export = function() {
  487. var defaults = this.defaults;
  488. var self = this;
  489. // export categories as .js
  490. async_map(defaults.compile, function(stFile, callback) {
  491. var category = path.basename(stFile, '.st');
  492. var jsFilePath = defaults.output_dir;
  493. if (undefined === jsFilePath) {
  494. jsFilePath = path.dirname(stFile);
  495. }
  496. var jsFile = category + defaults.suffix_used + '.js';
  497. jsFile = path.join(jsFilePath, jsFile);
  498. defaults.compiled.push(jsFile);
  499. var jsFileDeploy = category + defaults.suffix_used + '.deploy.js';
  500. jsFileDeploy = path.join(jsFilePath, jsFileDeploy);
  501. console.log('Exporting ' + (defaults.deploy ? '(debug + deploy)' : '(debug)')
  502. + ' category ' + category + ' as ' + jsFile
  503. + (defaults.deploy ? ' and ' + jsFileDeploy : ''));
  504. var smalltalk = defaults.smalltalk;
  505. var pluggableExporter = smalltalk.PluggableExporter;
  506. var packageObject = smalltalk.Package._named_(category);
  507. fs.writeFile(jsFile, smalltalk.String._streamContents_(function (stream) {
  508. pluggableExporter._newUsing_(smalltalk.Exporter._recipe())._exportPackage_on_(packageObject, stream); }), function(err) {
  509. if (defaults.deploy) {
  510. fs.writeFile(jsFileDeploy, smalltalk.String._streamContents_(function (stream) {
  511. pluggableExporter._newUsing_(smalltalk.StrippedExporter._recipe())._exportPackage_on_(packageObject, stream); }), callback);
  512. } else {
  513. callback(null, null);
  514. }
  515. });
  516. }, function(err, result){
  517. self.verify();
  518. });
  519. };
  520. /**
  521. * Verify if all .st files have been compiled.
  522. * Followed by compose_js_files() and optimize().
  523. */
  524. AmberC.prototype.verify = function() {
  525. console.log('Verifying if all .st files were compiled');
  526. var self = this;
  527. // copy array
  528. var compiledFiles = this.defaults.compiled.slice(0);
  529. // append deploy files if necessary
  530. if (true === this.defaults.deploy) {
  531. this.defaults.compiled.forEach(function(file) {
  532. compiledFiles.push(file.replace(/\.js/g, '.deploy.js'));
  533. });
  534. }
  535. async_map(compiledFiles,
  536. function(file, callback) {
  537. fs.exists(file, function(exists) {
  538. if (exists)
  539. callback(null, null);
  540. else
  541. throw(new Error('Compilation failed of: ' + file));
  542. });
  543. }, function(err, result) {
  544. self.compose_js_files();
  545. });
  546. };
  547. /**
  548. * Synchronous function.
  549. * Concatenates compiled JavaScript files into one file in the correct order.
  550. * The name of the produced file is given by defaults.program (set by the last commandline option).
  551. */
  552. AmberC.prototype.compose_js_files = function() {
  553. var defaults = this.defaults;
  554. var self = this;
  555. var programFile = defaults.program;
  556. if (undefined === programFile) {
  557. self.optimize();
  558. return;
  559. }
  560. if (undefined !== defaults.output_dir) {
  561. programFile = path.join(defaults.output_dir, programFile);
  562. }
  563. var program_files = [];
  564. if (0 !== defaults.libraries.length) {
  565. console.log('Collecting libraries: ' + defaults.libraries);
  566. program_files.push.apply(program_files, defaults.libraries);
  567. }
  568. if (0 !== defaults.compiled.length) {
  569. var compiledFiles = defaults.compiled.slice(0);
  570. if (true === defaults.deploy) {
  571. compiledFiles = compiledFiles.map(function(file) {
  572. return file.replace(/\.js$/g, '.deploy.js');
  573. });
  574. }
  575. console.log('Collecting compiled files: ' + compiledFiles);
  576. program_files.push.apply(program_files, compiledFiles);
  577. }
  578. console.ambercLog('Writing program file: %s.js', programFile);
  579. var fileStream = fs.createWriteStream(programFile + defaults.suffix_used + '.js');
  580. fileStream.on('error', function(error) {
  581. fileStream.end();
  582. console.ambercLog(error);
  583. });
  584. fileStream.on('close', function(){
  585. self.optimize();
  586. });
  587. var builder = createConcatenator();
  588. builder.start();
  589. program_files.forEach(function(file) {
  590. if(fs.existsSync(file)) {
  591. console.log('Adding : ' + file);
  592. var buffer = fs.readFileSync(file);
  593. // matches and returns the "module_id" string in the AMD define: define("module_id", ...)
  594. var match = buffer.toString().match(/^define\("([^"]*)"/);
  595. if (match /*&& match[1].slice(0,9) !== "amber_vm/"*/) {
  596. builder.addId(match[1]);
  597. }
  598. builder.add(buffer);
  599. } else {
  600. fileStream.end();
  601. throw(new Error('Can not find file ' + file));
  602. }
  603. });
  604. var mainFunctionOrFile = '';
  605. if (undefined !== defaults.main) {
  606. console.log('Adding call to: %s>>main', defaults.main);
  607. mainFunctionOrFile += 'smalltalk.' + defaults.main + '._main();';
  608. }
  609. if (undefined !== defaults.mainfile && fs.existsSync(defaults.mainfile)) {
  610. console.log('Adding main file: ' + defaults.mainfile);
  611. mainFunctionOrFile += '\n' + fs.readFileSync(defaults.mainfile);
  612. }
  613. builder.finish(mainFunctionOrFile);
  614. console.log('Writing...');
  615. builder.forEach(function (element) {
  616. fileStream.write(element);
  617. fileStream.write('\n');
  618. });
  619. console.log('Done.');
  620. fileStream.end();
  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.log = console.ambercLog;
  631. console.timeEnd('Compile Time');
  632. if (undefined !== defaults.finished_callback) {
  633. defaults.finished_callback();
  634. }
  635. });
  636. if (defaults.closure_parts) {
  637. console.log('Compiling all js files using Google closure compiler.');
  638. defaults.compiled.forEach(function(file) {
  639. var deployFile = file.replace(/\.js$/g, '.deploy.js');
  640. console.log('Compiling ' + deployFile + ' file using Google closure compiler.');
  641. var minifiedName = deployFile.replace(/\.js$/g, '.min.js');
  642. self.closure_compile(deployFile, minifiedName, optimization_done.add());
  643. });
  644. }
  645. if (defaults.closure_full && (undefined !== defaults.program)) {
  646. var programFile = defaults.program;
  647. if (undefined !== defaults.output_dir) {
  648. programFile = path.join(defaults.output_dir, programFile);
  649. }
  650. console.log('Compiling ' + programFile + '.js file using Google closure compiler.');
  651. self.closure_compile(programFile + '.js', programFile + '.min.js', optimization_done.add());
  652. }
  653. always_resolve(optimization_done.add());
  654. };
  655. /**
  656. * Compile sourceFile into minifiedFile with Google Closure compiler.
  657. * callback gets executed once finished.
  658. */
  659. AmberC.prototype.closure_compile = function(sourceFile, minifiedFile, callback) {
  660. // exec is asynchronous
  661. var self = this;
  662. exec(
  663. 'java -jar ' +
  664. self.closure_jar + ' ' +
  665. self.defaults.closure_options +
  666. ' --js '+ sourceFile +
  667. ' --js_output_file '+ minifiedFile,
  668. function (error, stdout, stderr) {
  669. if (error) {
  670. console.log(stderr);
  671. } else {
  672. console.log(stdout);
  673. console.log('Minified: '+ minifiedFile);
  674. }
  675. callback();
  676. }
  677. );
  678. };
  679. module.exports.Compiler = AmberC;
  680. module.exports.createDefaults = createDefaults;
  681. module.exports.Combo = Combo;
  682. module.exports.map = async_map;