2
0

amberc.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. return {
  56. elements: [],
  57. ids: [],
  58. add: function () {
  59. this.elements.push.apply(this.elements, arguments);
  60. },
  61. addId: function () {
  62. this.ids.push.apply(this.ids, arguments);
  63. },
  64. forEach: function () {
  65. this.elements.forEach.apply(this.elements, arguments);
  66. },
  67. start: function () {
  68. this.add(
  69. 'var define = (' + require('amdefine') + ')(), requirejs = define.require;',
  70. 'define("amber_vm/browser-compatibility", [], {});'
  71. );
  72. },
  73. finish: function (realWork) {
  74. this.add(
  75. 'define("amber_vm/_init", ["amber_vm/smalltalk","' + this.ids.join('","') + '"], function (smalltalk) {',
  76. 'smalltalk.initialize();',
  77. realWork,
  78. '});',
  79. 'requirejs("amber_vm/_init");'
  80. );
  81. },
  82. toString: function () {
  83. return this.elements.join('\n');
  84. }
  85. };
  86. }
  87. /**
  88. * Combine several async functions and evaluate callback once all of them have finished.
  89. * Taken from: http://howtonode.org/control-flow
  90. */
  91. function Combo(callback) {
  92. this.callback = callback;
  93. this.items = 0;
  94. this.results = [];
  95. }
  96. Combo.prototype = {
  97. add: function () {
  98. var self = this,
  99. id = this.items;
  100. this.items++;
  101. return function () {
  102. self.check(id, arguments);
  103. };
  104. },
  105. check: function (id, arguments) {
  106. this.results[id] = Array.prototype.slice.call(arguments);
  107. this.items--;
  108. if (this.items == 0) {
  109. this.callback.apply(this, this.results);
  110. }
  111. }
  112. };
  113. var path = require('path'),
  114. util = require('util'),
  115. fs = require('fs'),
  116. exec = require('child_process').exec;
  117. /**
  118. * AmberC constructor function.
  119. * amber_dir: points to the location of an amber installation
  120. */
  121. function AmberC(amber_dir) {
  122. if (undefined === amber_dir || !fs.existsSync(amber_dir)) {
  123. throw new Error('amber_dir needs to be a valid directory');
  124. }
  125. this.amber_dir = amber_dir;
  126. this.kernel_libraries = ['boot', 'smalltalk', 'nil', '_st', 'Kernel-Objects', 'Kernel-Classes', 'Kernel-Methods',
  127. 'Kernel-Collections', 'Kernel-Infrastructure', 'Kernel-Exceptions', 'Kernel-Transcript',
  128. 'Kernel-Announcements'];
  129. this.compiler_libraries = this.kernel_libraries.concat(['parser', 'Importer-Exporter', 'Compiler-Exceptions',
  130. 'Compiler-Core', 'Compiler-AST', 'Compiler-Exceptions', 'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic']);
  131. }
  132. /**
  133. * Default values.
  134. */
  135. var createDefaults = function(finished_callback){
  136. return {
  137. 'load': [],
  138. 'main': undefined,
  139. 'mainfile': undefined,
  140. 'stFiles': [],
  141. 'jsFiles': [],
  142. 'jsGlobals': [],
  143. 'amd_namespace': 'amber_core',
  144. 'suffix': '',
  145. 'loadsuffix': '',
  146. 'suffix_used': '',
  147. 'libraries': [],
  148. 'jsLibraryDirs': [],
  149. 'compile': [],
  150. 'compiled': [],
  151. 'program': undefined,
  152. 'output_dir': undefined,
  153. 'verbose': false,
  154. 'finished_callback': finished_callback
  155. };
  156. };
  157. /**
  158. * Main function for executing the compiler.
  159. * If check_configuration_ok() returns successfully the configuration is set on the current compiler
  160. * instance and check_for_closure_compiler() gets called.
  161. * The last step is to call collect_files().
  162. */
  163. AmberC.prototype.main = function(configuration, finished_callback) {
  164. console.time('Compile Time');
  165. if (undefined !== finished_callback) {
  166. configuration.finished_callback = finished_callback;
  167. }
  168. if (configuration.amd_namespace.length == 0) {
  169. configuration.amd_namespace = 'amber_core';
  170. }
  171. if (undefined !== configuration.jsLibraryDirs) {
  172. configuration.jsLibraryDirs.push(path.join(this.amber_dir, 'js'));
  173. configuration.jsLibraryDirs.push(path.join(this.amber_dir, 'support'));
  174. }
  175. console.ambercLog = console.log;
  176. if (false === configuration.verbose) {
  177. console.log = function() {};
  178. }
  179. if (this.check_configuration_ok(configuration)) {
  180. this.defaults = configuration;
  181. this.defaults.smalltalk = {}; // the evaluated compiler will be stored in this variable (see create_compiler)
  182. this.collect_files(this.defaults.stFiles, this.defaults.jsFiles)
  183. }
  184. };
  185. /**
  186. * Check if the passed in configuration object has sufficient/nonconflicting values
  187. */
  188. AmberC.prototype.check_configuration_ok = function(configuration) {
  189. if (undefined === configuration) {
  190. throw new Error('AmberC.check_configuration_ok(): missing configuration object');
  191. }
  192. if (0 === configuration.jsFiles.length && 0 === configuration.stFiles.lenght) {
  193. throw new Error('AmberC.check_configuration_ok(): no files to compile/link specified in configuration object');
  194. }
  195. return true;
  196. };
  197. /**
  198. * Check if the file given as parameter exists in any of the following directories:
  199. * 1. current local directory
  200. * 2. defauls.jsLibraryDirs
  201. * 3. $AMBER/js/
  202. * 3. $AMBER/support/
  203. *
  204. * @param filename name of a file without '.js' prefix
  205. * @param callback gets called on success with path to .js file as parameter
  206. */
  207. AmberC.prototype.resolve_js = function(filename, callback) {
  208. var baseName = path.basename(filename, '.js');
  209. var jsFile = baseName + this.defaults.loadsuffix + '.js';
  210. var defaults = this.defaults;
  211. console.log('Resolving: ' + jsFile);
  212. fs.exists(jsFile, function(exists) {
  213. if (exists) {
  214. callback(jsFile);
  215. } else {
  216. var amberJsFile = '';
  217. // check for specified .js file in any of the directories from jsLibraryDirs
  218. var found = defaults.jsLibraryDirs.some(function(directory) {
  219. amberJsFile = path.join(directory, jsFile);
  220. return fs.existsSync(amberJsFile);
  221. });
  222. if (found) {
  223. callback(amberJsFile);
  224. } else {
  225. throw(new Error('JavaScript file not found: ' + jsFile));
  226. }
  227. }
  228. });
  229. };
  230. /**
  231. * Collect libraries and Smalltalk files looking
  232. * both locally and in $AMBER/js and $AMBER/st.
  233. * Followed by resolve_libraries().
  234. */
  235. AmberC.prototype.collect_files = function(stFiles, jsFiles) {
  236. var self = this;
  237. var collected_files = new Combo(function() {
  238. self.resolve_libraries();
  239. });
  240. if (0 !== stFiles.length) {
  241. self.collect_st_files(stFiles, collected_files.add());
  242. }
  243. if (0 !== jsFiles.length) {
  244. self.collect_js_files(jsFiles, collected_files.add());
  245. }
  246. };
  247. /**
  248. * Resolve st files given by stFiles and add them to defaults.compile.
  249. * Respective categories get added to defaults.compile_categories.
  250. * callback is evaluated afterwards.
  251. */
  252. AmberC.prototype.collect_st_files = function(stFiles, callback) {
  253. var defaults = this.defaults;
  254. var self = this;
  255. var collected_st_files = new Combo(function() {
  256. Array.prototype.slice.call(arguments).forEach(function(data) {
  257. var stFile = data[0];
  258. defaults.compile.push(stFile);
  259. });
  260. callback();
  261. });
  262. stFiles.forEach(function(stFile) {
  263. var _callback = collected_st_files.add();
  264. console.log('Checking: ' + stFile);
  265. var amberStFile = path.join(self.amber_dir, 'st', stFile);
  266. fs.exists(stFile, function(exists) {
  267. if (exists) {
  268. _callback(stFile);
  269. } else {
  270. console.log('Checking: ' + amberStFile);
  271. fs.exists(amberStFile, function(exists) {
  272. if (exists) {
  273. _callback(amberStFile);
  274. } else {
  275. throw(new Error('Smalltalk file not found: ' + amberStFile));
  276. }
  277. });
  278. }
  279. });
  280. });
  281. };
  282. /**
  283. * Resolve js files given by jsFiles and add them to defaults.libraries.
  284. * callback is evaluated afterwards.
  285. */
  286. AmberC.prototype.collect_js_files = function(jsFiles, callback) {
  287. var self = this;
  288. var collected_js_files = new Combo(function() {
  289. Array.prototype.slice.call(arguments).forEach(function(file) {
  290. self.defaults.libraries.push(file[0]);
  291. });
  292. callback();
  293. });
  294. jsFiles.forEach(function(jsFile) {
  295. self.resolve_js(jsFile, collected_js_files.add());
  296. });
  297. };
  298. /**
  299. * Resolve kernel and compiler files.
  300. * Followed by resolve_init().
  301. */
  302. AmberC.prototype.resolve_libraries = function() {
  303. // Resolve libraries listed in this.kernel_libraries
  304. var self = this;
  305. var all_resolved = new Combo(function(resolved_kernel_files, resolved_compiler_files) {
  306. self.create_compiler(resolved_compiler_files[0]);
  307. });
  308. this.resolve_kernel(all_resolved.add());
  309. this.resolve_compiler(all_resolved.add());
  310. };
  311. /**
  312. * Resolve .js files needed by kernel
  313. * callback is evaluated afterwards.
  314. */
  315. AmberC.prototype.resolve_kernel = function(callback) {
  316. var self = this;
  317. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  318. var kernel_resolved = new Combo(function() {
  319. var foundLibraries = [];
  320. Array.prototype.slice.call(arguments).forEach(function(file) {
  321. if (undefined !== file[0]) {
  322. foundLibraries.push(file[0]);
  323. }
  324. });
  325. // boot.js and Kernel files need to be used first
  326. // otherwise the global smalltalk object is undefined
  327. self.defaults.libraries = foundLibraries.concat(self.defaults.libraries);
  328. callback(null);
  329. });
  330. kernel_files.forEach(function(file) {
  331. self.resolve_js(file, kernel_resolved.add());
  332. });
  333. always_resolve(kernel_resolved.add());
  334. };
  335. /**
  336. * Resolve .js files needed by compiler.
  337. * callback is evaluated afterwards with resolved files as argument.
  338. */
  339. AmberC.prototype.resolve_compiler = function(callback) {
  340. // Resolve compiler libraries
  341. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  342. var compiler_resolved = new Combo(function() {
  343. var compilerFiles = [];
  344. Array.prototype.slice.call(arguments).forEach(function(file) {
  345. if (undefined !== file[0]) {
  346. compilerFiles.push(file[0]);
  347. }
  348. });
  349. callback(compilerFiles);
  350. });
  351. var self = this
  352. compiler_files.forEach(function(file) {
  353. self.resolve_js(file, compiler_resolved.add());
  354. });
  355. always_resolve(compiler_resolved.add());
  356. };
  357. /**
  358. * Read all .js files needed by compiler and eval() them.
  359. * The finished Compiler gets stored in defaults.smalltalk.
  360. * Followed by compile().
  361. */
  362. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  363. var self = this;
  364. var compiler_files = new Combo(function() {
  365. var builder = createConcatenator();
  366. builder.add('(function() {');
  367. builder.start();
  368. Array.prototype.slice.call(arguments).forEach(function(data) {
  369. // data is an array where index 0 is the error code and index 1 contains the data
  370. builder.add(data[1]);
  371. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  372. var match = ('' + data[1]).match(/^define\("([^"]*)"/);
  373. if (match) {
  374. builder.addId(match[1]);
  375. }
  376. });
  377. // store the generated smalltalk env in self.defaults.smalltalk
  378. builder.finish('self.defaults.smalltalk = smalltalk;');
  379. builder.add('})();');
  380. eval(builder.toString());
  381. console.log('Compiler loaded');
  382. self.defaults.smalltalk.ErrorHandler._setCurrent_(self.defaults.smalltalk.RethrowErrorHandler._new());
  383. if(0 != self.defaults.jsGlobals.length) {
  384. var jsGlobalVariables = self.defaults.smalltalk.globalJsVariables;
  385. jsGlobalVariables.push.apply(jsGlobalVariables, self.defaults.jsGlobals);
  386. }
  387. self.compile();
  388. });
  389. compilerFilesArray.forEach(function(file) {
  390. console.log('Loading file: ' + file);
  391. fs.readFile(file, compiler_files.add());
  392. });
  393. };
  394. /**
  395. * Compile all given .st files by importing them.
  396. * Followed by category_export().
  397. */
  398. AmberC.prototype.compile = function() {
  399. console.log('Compiling collected .st files')
  400. // import .st files
  401. var self = this;
  402. var imports = new Combo(function() {
  403. Array.prototype.slice.call(arguments).forEach(function(code) {
  404. if (undefined !== code[0]) {
  405. // get element 0 of code since all return values are stored inside an array by Combo
  406. self.defaults.smalltalk.Importer._new()._import_(code[0]._stream());
  407. }
  408. });
  409. self.category_export();
  410. });
  411. this.defaults.compile.forEach(function(stFile) {
  412. var callback = imports.add();
  413. if (/\.st/.test(stFile)) {
  414. console.ambercLog('Importing: ' + stFile);
  415. fs.readFile(stFile, 'utf8', function(err, data) {
  416. if (!err)
  417. callback(data);
  418. else
  419. throw new Error('Could not import: ' + stFile);
  420. });
  421. }
  422. });
  423. always_resolve(imports.add());
  424. };
  425. /**
  426. * Export compiled categories to JavaScript files.
  427. * Followed by verify().
  428. */
  429. AmberC.prototype.category_export = function() {
  430. var defaults = this.defaults;
  431. var self = this;
  432. // export categories as .js
  433. async_map(defaults.compile, function(stFile, callback) {
  434. var category = path.basename(stFile, '.st');
  435. var jsFilePath = defaults.output_dir;
  436. if (undefined === jsFilePath) {
  437. jsFilePath = path.dirname(stFile);
  438. }
  439. var jsFile = category + defaults.suffix_used + '.js';
  440. jsFile = path.join(jsFilePath, jsFile);
  441. defaults.compiled.push(jsFile);
  442. var smalltalk = defaults.smalltalk;
  443. var pluggableExporter = smalltalk.PluggableExporter;
  444. var packageObject = smalltalk.Package._named_(category);
  445. packageObject._transport()._namespace_(defaults.amd_namespace);
  446. fs.writeFile(jsFile, smalltalk.String._streamContents_(function (stream) {
  447. smalltalk.AmdExporter._new()._exportPackage_on_(packageObject, stream); }), function(err) {
  448. callback(null, null);
  449. });
  450. }, function(err, result){
  451. self.verify();
  452. });
  453. };
  454. /**
  455. * Verify if all .st files have been compiled.
  456. * Followed by compose_js_files().
  457. */
  458. AmberC.prototype.verify = function() {
  459. console.log('Verifying if all .st files were compiled');
  460. var self = this;
  461. // copy array
  462. var compiledFiles = this.defaults.compiled.slice(0);
  463. async_map(compiledFiles,
  464. function(file, callback) {
  465. fs.exists(file, function(exists) {
  466. if (exists)
  467. callback(null, null);
  468. else
  469. throw(new Error('Compilation failed of: ' + file));
  470. });
  471. }, function(err, result) {
  472. self.compose_js_files();
  473. });
  474. };
  475. /**
  476. * Synchronous function.
  477. * Concatenates compiled JavaScript files into one file in the correct order.
  478. * The name of the produced file is given by defaults.program (set by the last commandline option).
  479. */
  480. AmberC.prototype.compose_js_files = function() {
  481. var defaults = this.defaults;
  482. var self = this;
  483. var programFile = defaults.program;
  484. if (undefined === programFile) {
  485. return;
  486. }
  487. if (undefined !== defaults.output_dir) {
  488. programFile = path.join(defaults.output_dir, programFile);
  489. }
  490. var program_files = [];
  491. if (0 !== defaults.libraries.length) {
  492. console.log('Collecting libraries: ' + defaults.libraries);
  493. program_files.push.apply(program_files, defaults.libraries);
  494. }
  495. if (0 !== defaults.compiled.length) {
  496. var compiledFiles = defaults.compiled.slice(0);
  497. console.log('Collecting compiled files: ' + compiledFiles);
  498. program_files.push.apply(program_files, compiledFiles);
  499. }
  500. console.ambercLog('Writing program file: %s.js', programFile);
  501. var fileStream = fs.createWriteStream(programFile + defaults.suffix_used + '.js');
  502. fileStream.on('error', function(error) {
  503. fileStream.end();
  504. console.ambercLog(error);
  505. });
  506. fileStream.on('close', function(){
  507. return;
  508. });
  509. var builder = createConcatenator();
  510. builder.add('#!/usr/bin/env node');
  511. builder.start();
  512. program_files.forEach(function(file) {
  513. if(fs.existsSync(file)) {
  514. console.log('Adding : ' + file);
  515. var buffer = fs.readFileSync(file);
  516. // matches and returns the "module_id" string in the AMD define: define("module_id", ...)
  517. var match = buffer.toString().match(/^define\("([^"]*)"/);
  518. if (match /*&& match[1].slice(0,9) !== "amber_vm/"*/) {
  519. builder.addId(match[1]);
  520. }
  521. builder.add(buffer);
  522. } else {
  523. fileStream.end();
  524. throw(new Error('Can not find file ' + file));
  525. }
  526. });
  527. var mainFunctionOrFile = '';
  528. if (undefined !== defaults.main) {
  529. console.log('Adding call to: %s>>main', defaults.main);
  530. mainFunctionOrFile += 'smalltalk.' + defaults.main + '._main();';
  531. }
  532. if (undefined !== defaults.mainfile && fs.existsSync(defaults.mainfile)) {
  533. console.log('Adding main file: ' + defaults.mainfile);
  534. mainFunctionOrFile += '\n' + fs.readFileSync(defaults.mainfile);
  535. }
  536. builder.finish(mainFunctionOrFile);
  537. console.log('Writing...');
  538. builder.forEach(function (element) {
  539. fileStream.write(element);
  540. fileStream.write('\n');
  541. });
  542. console.log('Done.');
  543. fileStream.end();
  544. };
  545. module.exports.Compiler = AmberC;
  546. module.exports.createDefaults = createDefaults;
  547. module.exports.Combo = Combo;
  548. module.exports.map = async_map;