1
0

amberc.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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', 'Importer-Exporter', '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. if (undefined === amber_dir) {
  89. throw new Error('createDefaults() function needs a valid amber_dir parameter');
  90. }
  91. return {
  92. 'load': [],
  93. 'init': path.join(amber_dir, 'js', 'init.js'),
  94. 'main': undefined,
  95. 'mainfile': undefined,
  96. 'stFiles': [],
  97. 'jsFiles': [],
  98. 'closure': false,
  99. 'closure_parts': false,
  100. 'closure_full': false,
  101. 'closure_options': ' --language_in=ECMASCRIPT5 ',
  102. 'suffix': '',
  103. 'loadsuffix': '',
  104. 'suffix_used': '',
  105. 'deploy': false,
  106. 'libraries': [],
  107. 'compile': [],
  108. 'compiled_categories': [],
  109. 'compiled': [],
  110. 'program': undefined,
  111. 'finished_callback': finished_callback
  112. };
  113. };
  114. /**
  115. * Main function for executing the compiler.
  116. */
  117. AmberC.prototype.main = function(configuration, finished_callback) {
  118. console.time('Compile Time');
  119. if (undefined !== finished_callback) {
  120. configuration.finished_callback = finished_callback;
  121. }
  122. if (this.check_configuration_ok(configuration)) {
  123. this.defaults = configuration;
  124. this.defaults.smalltalk = {}; // the evaluated compiler will be stored in this variable (see create_compiler)
  125. var self = this;
  126. this.check_for_closure_compiler(function(){
  127. self.collect_files(self.defaults.stFiles, self.defaults.jsFiles)
  128. });
  129. }
  130. };
  131. /**
  132. * Check if the passed in configuration object has sufficient/nonconflicting values
  133. */
  134. AmberC.prototype.check_configuration_ok = function(configuration) {
  135. if (undefined === configuration) {
  136. throw new Error('AmberC.check_configuration_ok(): missing configuration object');
  137. }
  138. if (undefined === configuration.init) {
  139. throw new Error('AmberC.check_configuration_ok(): init value missing in configuration object');
  140. }
  141. if (0 === configuration.jsFiles.length && 0 === configuration.stFiles.lenght) {
  142. throw new Error('AmberC.check_configuration_ok(): no files to compile/link specified in configuration object');
  143. }
  144. return true;
  145. };
  146. /**
  147. * Checks if the java executable exists and afterwards,
  148. * if compiler.jar exists at the path stored in this.closure_jar.
  149. * All closure related entries are set to false upon failure.
  150. *
  151. * callback gets called in any case.
  152. */
  153. AmberC.prototype.check_for_closure_compiler = function(callback) {
  154. var defaults = this.defaults;
  155. var self = this;
  156. if (defaults.closure) {
  157. exec('which java', function(error, stdout, stderr) {
  158. // stdout contains path to java executable
  159. if (null !== error) {
  160. console.warn('java is not installed but is needed for -O, -A or -o (Closure compiler).');
  161. defaults.closure = false;
  162. defaults.closure_parts = false;
  163. defaults.closure_full = false;
  164. callback();
  165. return;
  166. }
  167. path.exists(self.closure_jar, function(exists) {
  168. if (!exists) {
  169. console.warn('Can not find Closure compiler at: ' + self.closure_jar);
  170. defaults.closure = false;
  171. defaults.closure_parts = false;
  172. defaults.closure_full = false;
  173. } else {
  174. console.warn('Closure compiler found at: ' + self.closure_jar);
  175. }
  176. callback();
  177. return;
  178. });
  179. });
  180. } else {
  181. callback();
  182. }
  183. };
  184. /**
  185. * Check if the file given as parameter exists in the local directory or in $AMBER/js/.
  186. * '.js' is appended first.
  187. *
  188. * @param filename name of a file without '.js' prefix
  189. * @param callback gets called on success with path to .js file as parameter
  190. */
  191. AmberC.prototype.resolve_js = function(filename, callback) {
  192. var baseName = path.basename(filename, '.js');
  193. var jsFile = baseName + this.defaults.loadsuffix + '.js';
  194. var amberJsFile = path.join(this.amber_dir, 'js', jsFile);
  195. console.log('Resolving: ' + jsFile);
  196. path.exists(jsFile, function(exists) {
  197. if (exists) {
  198. callback(jsFile);
  199. } else {
  200. path.exists(amberJsFile, function(exists) {
  201. if (exists) {
  202. callback(amberJsFile);
  203. } else {
  204. throw(new Error('JavaScript file not found: ' + jsFile));
  205. }
  206. });
  207. }
  208. });
  209. };
  210. /**
  211. * Collect libraries and Smalltalk files looking
  212. * both locally and in $AMBER/js and $AMBER/st.
  213. * Followed by resolve_libraries().
  214. */
  215. AmberC.prototype.collect_files = function(stFiles, jsFiles) {
  216. var self = this;
  217. var collected_files = new Combo(function() {
  218. self.resolve_libraries();
  219. });
  220. if (0 !== stFiles.length) {
  221. self.collect_st_files(stFiles, collected_files.add());
  222. }
  223. if (0 !== jsFiles.length) {
  224. self.collect_js_files(jsFiles, collected_files.add());
  225. }
  226. };
  227. /**
  228. * Resolve st files given by stFiles and add them to defaults.compile.
  229. * Respective categories get added to defaults.compile_categories.
  230. * callback is evaluated afterwards.
  231. */
  232. AmberC.prototype.collect_st_files = function(stFiles, callback) {
  233. var defaults = this.defaults;
  234. var self = this;
  235. var collected_st_files = new Combo(function() {
  236. Array.prototype.slice.call(arguments).forEach(function(data) {
  237. var stFile = data[0];
  238. var stCategory = data[1];
  239. defaults.compile.push(stFile);
  240. defaults.compiled_categories.push(stCategory);
  241. defaults.compiled.push(stCategory + defaults.suffix_used + '.js');
  242. });
  243. callback();
  244. });
  245. stFiles.forEach(function(stFile) {
  246. var _callback = collected_st_files.add();
  247. console.log('Checking: ' + stFile);
  248. var category = path.basename(stFile, '.st');
  249. var amberStFile = path.join(self.amber_dir, 'st', stFile);
  250. path.exists(stFile, function(exists) {
  251. if (exists) {
  252. _callback(stFile, category);
  253. } else {
  254. path.exists(amberStFile, function(exists) {
  255. if (exists) {
  256. _callback(amberStFile, category);
  257. } else {
  258. throw(new Error('Smalltalk file not found: ' + amberStFile));
  259. }
  260. });
  261. }
  262. });
  263. });
  264. };
  265. /**
  266. * Resolve js files given by jsFiles and add them to defaults.libraries.
  267. * callback is evaluated afterwards.
  268. */
  269. AmberC.prototype.collect_js_files = function(jsFiles, callback) {
  270. var self = this;
  271. var collected_js_files = new Combo(function() {
  272. Array.prototype.slice.call(arguments).forEach(function(file) {
  273. self.defaults.libraries.push(file[0]);
  274. });
  275. callback();
  276. });
  277. jsFiles.forEach(function(jsFile) {
  278. self.resolve_js(jsFile, collected_js_files.add());
  279. });
  280. };
  281. /**
  282. * Resolve kernel and compiler files.
  283. * Followed by resolve_init().
  284. */
  285. AmberC.prototype.resolve_libraries = function() {
  286. // Resolve libraries listed in this.kernel_libraries
  287. var self = this;
  288. var all_resolved = new Combo(function(resolved_library_files, resolved_compiler_files) {
  289. self.resolve_init(resolved_compiler_files[0]);
  290. });
  291. this.resolve_kernel(all_resolved.add());
  292. this.resolve_compiler(all_resolved.add());
  293. };
  294. /**
  295. * Resolve .js files needed by kernel
  296. * callback is evaluated afterwards.
  297. */
  298. AmberC.prototype.resolve_kernel = function(callback) {
  299. var self = this;
  300. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  301. var kernel_resolved = new Combo(function() {
  302. Array.prototype.slice.call(arguments).forEach(function(file) {
  303. if (undefined !== file[0]) {
  304. self.defaults.libraries.push(file[0]);
  305. }
  306. });
  307. callback(null);
  308. });
  309. kernel_files.forEach(function(file) {
  310. self.resolve_js(file, kernel_resolved.add());
  311. });
  312. always_resolve(kernel_resolved.add());
  313. };
  314. /**
  315. * Resolve .js files needed by compiler.
  316. * callback is evaluated afterwards with resolved files as argument.
  317. */
  318. AmberC.prototype.resolve_compiler = function(callback) {
  319. // Resolve compiler libraries
  320. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  321. var compiler_resolved = new Combo(function() {
  322. var compilerFiles = [];
  323. Array.prototype.slice.call(arguments).forEach(function(file) {
  324. if (undefined !== file[0]) {
  325. compilerFiles.push(file[0]);
  326. }
  327. });
  328. callback(compilerFiles);
  329. });
  330. var self = this
  331. compiler_files.forEach(function(file) {
  332. self.resolve_js(file, compiler_resolved.add());
  333. });
  334. always_resolve(compiler_resolved.add());
  335. };
  336. /**
  337. * Resolves default.init and adds it to compilerFiles.
  338. * Followed by create_compiler().
  339. */
  340. AmberC.prototype.resolve_init = function(compilerFiles) {
  341. // check and add init.js
  342. var initFile = this.defaults.init;
  343. if ('.js' !== path.extname(initFile)) {
  344. initFile = this.resolve_js(initFile);
  345. this.defaults.init = initFile;
  346. }
  347. compilerFiles.push(initFile);
  348. this.create_compiler(compilerFiles);
  349. };
  350. /**
  351. * Read all .js files needed by compiler and eval() them.
  352. * The finished Compiler gets stored in defaults.smalltalk.
  353. * Followed by compile().
  354. */
  355. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  356. var self = this;
  357. var compiler_files = new Combo(function() {
  358. var content = '(function() {';
  359. Array.prototype.slice.call(arguments).forEach(function(data) {
  360. // data is an array where index 0 is the error code and index 1 contains the data
  361. content += data[1];
  362. });
  363. content = content + 'return smalltalk;})();';
  364. self.defaults.smalltalk = eval(content);
  365. console.log('Compiler loaded');
  366. self.defaults.smalltalk.ErrorHandler._setCurrent_(self.defaults.smalltalk.RethrowErrorHandler._new());
  367. self.compile();
  368. });
  369. compilerFilesArray.forEach(function(file) {
  370. console.log('Loading file: ' + file);
  371. fs.readFile(file, compiler_files.add());
  372. });
  373. };
  374. /**
  375. * Compile all given .st files by importing them.
  376. * Followed by category_export().
  377. */
  378. AmberC.prototype.compile = function() {
  379. console.log('Compiling collected .st files')
  380. // import .st files
  381. var self = this;
  382. var imports = new Combo(function() {
  383. Array.prototype.slice.call(arguments).forEach(function(code) {
  384. if (undefined !== code[0]) {
  385. // get element 0 of code since all return values are stored inside an array by Combo
  386. self.defaults.smalltalk.Importer._new()._import_(code[0]._stream());
  387. }
  388. });
  389. self.category_export();
  390. });
  391. this.defaults.compile.forEach(function(stFile) {
  392. var callback = imports.add();
  393. if (/\.st/.test(stFile)) {
  394. console.log('Importing: ' + stFile);
  395. fs.readFile(stFile, 'utf8', function(err, data) {
  396. if (!err)
  397. callback(data);
  398. else
  399. throw new Error('Could not import: ' + stFile);
  400. });
  401. }
  402. });
  403. always_resolve(imports.add());
  404. };
  405. /**
  406. * Export compiled categories to JavaScript files.
  407. * Followed by verify().
  408. */
  409. AmberC.prototype.category_export = function() {
  410. var defaults = this.defaults;
  411. var self = this;
  412. // export categories as .js
  413. async_map(defaults.compiled_categories, function(category, callback) {
  414. var jsFile = category + defaults.suffix_used + '.js';
  415. var jsFileDeploy = category + defaults.suffix_used + '.deploy.js';
  416. console.log('Exporting ' + (defaults.deploy ? '(debug + deploy)' : '(debug)')
  417. + ' category ' + category + ' as ' + jsFile
  418. + (defaults.deploy ? ' and ' + jsFileDeploy : ''));
  419. fs.writeFile(jsFile, defaults.smalltalk.Exporter._new()._exportPackage_(category), function(err) {
  420. if (defaults.deploy) {
  421. fs.writeFile(jsFileDeploy, defaults.smalltalk.StrippedExporter._new()._exportPackage_(category), callback);
  422. } else {
  423. callback(null, null);
  424. }
  425. });
  426. }, function(err, result){
  427. self.verify();
  428. });
  429. };
  430. /**
  431. * Verify if all .st files have been compiled.
  432. * Followed by compose_js_files() and optimize().
  433. */
  434. AmberC.prototype.verify = function() {
  435. console.log('Verifying if all .st files were compiled');
  436. var self = this;
  437. async_map(this.defaults.compiled, function(file, callback) {
  438. path.exists(file, function(exists) {
  439. if (exists)
  440. callback(null, null);
  441. else
  442. throw(new Error('Compilation failed of: ' + file));
  443. });
  444. }, function(err, result) {
  445. self.compose_js_files();
  446. });
  447. };
  448. /**
  449. * Synchronous function.
  450. * Concatenates compiled JavaScript files into one file in the correct order.
  451. * The name of the produced file is given by defaults.program (set by the last commandline option).
  452. */
  453. AmberC.prototype.compose_js_files = function() {
  454. var defaults = this.defaults;
  455. var self = this;
  456. if (undefined === defaults.program) {
  457. self.optimize();
  458. return;
  459. }
  460. var program_files = [];
  461. if (0 !== defaults.libraries.length) {
  462. console.log('Collecting libraries: ' + defaults.libraries);
  463. program_files.push.apply(program_files, defaults.libraries);
  464. }
  465. if (0 !== defaults.compiled.length) {
  466. console.log('Collecting compiled files: ' + defaults.compiled);
  467. program_files.push.apply(program_files, defaults.compiled);
  468. }
  469. if (undefined !== defaults.init) {
  470. console.log('Adding initializer ' + defaults.init);
  471. program_files.push(defaults.init);
  472. }
  473. console.log('Writing program file: %s.js', defaults.program);
  474. var fileStream = fs.createWriteStream(defaults.program + defaults.suffix_used + '.js');
  475. fileStream.on('error', function(error) {
  476. fileStream.end();
  477. console.log(error);
  478. });
  479. fileStream.on('close', function(){
  480. self.optimize();
  481. });
  482. program_files.forEach(function(file) {
  483. if(path.existsSync(file)) {
  484. console.log('Adding : ' + file);
  485. fileStream.write(fs.readFileSync(file));
  486. } else {
  487. fileStream.end();
  488. throw(new Error('Can not find file ' + file));
  489. }
  490. });
  491. if (undefined !== defaults.main) {
  492. console.log('Adding call to: %s>>main', defaults.main);
  493. fileStream.write('smalltalk.' + defaults.main + '._main()');
  494. }
  495. if (undefined !== defaults.mainfile && path.existsSync(defaults.mainfile)) {
  496. console.log('Adding main file: ' + defaults.mainfile);
  497. fileStream.write(fs.readFileSync(defaults.mainfile));
  498. }
  499. console.log('Done.');
  500. fileStream.end();
  501. };
  502. /**
  503. * Optimize created JavaScript files with Google Closure compiler depending
  504. * on the flags: defaults.closure_parts, defaults.closure_full.
  505. */
  506. AmberC.prototype.optimize = function() {
  507. var defaults = this.defaults;
  508. var self = this;
  509. var optimization_done = new Combo(function() {
  510. console.timeEnd('Compile Time');
  511. if (undefined !== defaults.finished_callback) {
  512. defaults.finished_callback();
  513. }
  514. });
  515. if (defaults.closure_parts) {
  516. console.log('Compiling all js files using Google closure compiler.');
  517. defaults.compiled.forEach(function(file) {
  518. console.log('Compiling ' + file + ' file using Google closure compiler.');
  519. var minifiedName = path.basename(file, '.js') + '.min.js';
  520. self.closure_compile(file, minifiedName, optimization_done.add());
  521. });
  522. }
  523. if (defaults.closure_full && (undefined !== defaults.program)) {
  524. console.log('Compiling ' + defaults.program + '.js file using Google closure compiler.');
  525. self.closure_compile(defaults.program + '.js', defaults.program + '.min.js', optimization_done.add());
  526. }
  527. always_resolve(optimization_done.add());
  528. };
  529. /**
  530. * Compile sourceFile into minifiedFile with Google Closure compiler.
  531. * callback gets executed once finished.
  532. */
  533. AmberC.prototype.closure_compile = function(sourceFile, minifiedFile, callback) {
  534. // exec is asynchronous
  535. var self = this;
  536. exec(
  537. 'java -jar ' +
  538. self.closure_jar + ' ' +
  539. self.defaults.closure_options +
  540. ' --js '+ sourceFile +
  541. ' --js_output_file '+ minifiedFile,
  542. function (error, stdout, stderr) {
  543. if (error) {
  544. console.log(stderr);
  545. } else {
  546. console.log(stdout);
  547. console.log('Minified: '+ minifiedFile);
  548. }
  549. callback();
  550. }
  551. );
  552. };
  553. module.exports.Compiler = AmberC;
  554. module.exports.createDefaults = createDefaults;
  555. module.exports.Combo = Combo;
  556. module.exports.map = async_map;