1
0

amberc.js 18 KB

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