amberc.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. if (this.check_configuration_ok(configuration)) {
  181. this.defaults = configuration;
  182. this.defaults.smalltalk = {}; // the evaluated compiler will be stored in this variable (see create_compiler)
  183. this.collect_files(this.defaults.stFiles, this.defaults.jsFiles)
  184. }
  185. };
  186. /**
  187. * Check if the passed in configuration object has sufficient/nonconflicting values
  188. */
  189. AmberC.prototype.check_configuration_ok = function(configuration) {
  190. if (undefined === configuration) {
  191. throw new Error('AmberC.check_configuration_ok(): missing configuration object');
  192. }
  193. if (0 === configuration.jsFiles.length && 0 === configuration.stFiles.length) {
  194. throw new Error('AmberC.check_configuration_ok(): no files to compile/link specified in configuration object');
  195. }
  196. return true;
  197. };
  198. /**
  199. * Check if the file given as parameter exists in any of the following directories:
  200. * 1. current local directory
  201. * 2. defauls.jsLibraryDirs
  202. * 3. $AMBER/js/
  203. * 3. $AMBER/support/
  204. *
  205. * @param filename name of a file without '.js' prefix
  206. * @param callback gets called on success with path to .js file as parameter
  207. */
  208. AmberC.prototype.resolve_js = function(filename, callback) {
  209. var baseName = path.basename(filename, '.js');
  210. var jsFile = baseName + this.defaults.loadsuffix + '.js';
  211. var defaults = this.defaults;
  212. console.log('Resolving: ' + jsFile);
  213. fs.exists(jsFile, function(exists) {
  214. if (exists) {
  215. callback(jsFile);
  216. } else {
  217. var amberJsFile = '';
  218. // check for specified .js file in any of the directories from jsLibraryDirs
  219. var found = defaults.jsLibraryDirs.some(function(directory) {
  220. amberJsFile = path.join(directory, jsFile);
  221. return fs.existsSync(amberJsFile);
  222. });
  223. if (found) {
  224. callback(amberJsFile);
  225. } else {
  226. throw(new Error('JavaScript file not found: ' + jsFile));
  227. }
  228. }
  229. });
  230. };
  231. /**
  232. * Collect libraries and Smalltalk files looking
  233. * both locally and in $AMBER/js and $AMBER/st.
  234. * Followed by resolve_libraries().
  235. */
  236. AmberC.prototype.collect_files = function(stFiles, jsFiles) {
  237. var self = this;
  238. var collected_files = new Combo(function() {
  239. self.resolve_libraries();
  240. });
  241. if (0 !== stFiles.length) {
  242. self.collect_st_files(stFiles, collected_files.add());
  243. }
  244. if (0 !== jsFiles.length) {
  245. self.collect_js_files(jsFiles, collected_files.add());
  246. }
  247. };
  248. /**
  249. * Resolve st files given by stFiles and add them to defaults.compile.
  250. * Respective categories get added to defaults.compile_categories.
  251. * callback is evaluated afterwards.
  252. */
  253. AmberC.prototype.collect_st_files = function(stFiles, callback) {
  254. var defaults = this.defaults;
  255. var self = this;
  256. var collected_st_files = new Combo(function() {
  257. Array.prototype.slice.call(arguments).forEach(function(data) {
  258. var stFile = data[0];
  259. defaults.compile.push(stFile);
  260. });
  261. callback();
  262. });
  263. stFiles.forEach(function(stFile) {
  264. var _callback = collected_st_files.add();
  265. console.log('Checking: ' + stFile);
  266. var amberStFile = path.join(self.amber_dir, 'st', stFile);
  267. fs.exists(stFile, function(exists) {
  268. if (exists) {
  269. _callback(stFile);
  270. } else {
  271. console.log('Checking: ' + amberStFile);
  272. fs.exists(amberStFile, function(exists) {
  273. if (exists) {
  274. _callback(amberStFile);
  275. } else {
  276. throw(new Error('Smalltalk file not found: ' + amberStFile));
  277. }
  278. });
  279. }
  280. });
  281. });
  282. };
  283. /**
  284. * Resolve js files given by jsFiles and add them to defaults.libraries.
  285. * callback is evaluated afterwards.
  286. */
  287. AmberC.prototype.collect_js_files = function(jsFiles, callback) {
  288. var self = this;
  289. var collected_js_files = new Combo(function() {
  290. Array.prototype.slice.call(arguments).forEach(function(file) {
  291. self.defaults.libraries.push(file[0]);
  292. });
  293. callback();
  294. });
  295. jsFiles.forEach(function(jsFile) {
  296. self.resolve_js(jsFile, collected_js_files.add());
  297. });
  298. };
  299. /**
  300. * Resolve kernel and compiler files.
  301. * Followed by resolve_init().
  302. */
  303. AmberC.prototype.resolve_libraries = function() {
  304. // Resolve libraries listed in this.kernel_libraries
  305. var self = this;
  306. var all_resolved = new Combo(function(resolved_kernel_files, resolved_compiler_files) {
  307. self.create_compiler(resolved_compiler_files[0]);
  308. });
  309. this.resolve_kernel(all_resolved.add());
  310. this.resolve_compiler(all_resolved.add());
  311. };
  312. /**
  313. * Resolve .js files needed by kernel
  314. * callback is evaluated afterwards.
  315. */
  316. AmberC.prototype.resolve_kernel = function(callback) {
  317. var self = this;
  318. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  319. var kernel_resolved = new Combo(function() {
  320. var foundLibraries = [];
  321. Array.prototype.slice.call(arguments).forEach(function(file) {
  322. if (undefined !== file[0]) {
  323. foundLibraries.push(file[0]);
  324. }
  325. });
  326. // boot.js and Kernel files need to be used first
  327. // otherwise the global smalltalk object is undefined
  328. self.defaults.libraries = foundLibraries.concat(self.defaults.libraries);
  329. callback(null);
  330. });
  331. kernel_files.forEach(function(file) {
  332. self.resolve_js(file, kernel_resolved.add());
  333. });
  334. always_resolve(kernel_resolved.add());
  335. };
  336. /**
  337. * Resolve .js files needed by compiler.
  338. * callback is evaluated afterwards with resolved files as argument.
  339. */
  340. AmberC.prototype.resolve_compiler = function(callback) {
  341. // Resolve compiler libraries
  342. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  343. var compiler_resolved = new Combo(function() {
  344. var compilerFiles = [];
  345. Array.prototype.slice.call(arguments).forEach(function(file) {
  346. if (undefined !== file[0]) {
  347. compilerFiles.push(file[0]);
  348. }
  349. });
  350. callback(compilerFiles);
  351. });
  352. var self = this;
  353. compiler_files.forEach(function(file) {
  354. self.resolve_js(file, compiler_resolved.add());
  355. });
  356. always_resolve(compiler_resolved.add());
  357. };
  358. /**
  359. * Read all .js files needed by compiler and eval() them.
  360. * The finished Compiler gets stored in defaults.smalltalk.
  361. * Followed by compile().
  362. */
  363. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  364. var self = this;
  365. var compiler_files = new Combo(function() {
  366. var builder = createConcatenator();
  367. builder.add('(function() {');
  368. builder.start();
  369. Array.prototype.slice.call(arguments).forEach(function(data) {
  370. // data is an array where index 0 is the error code and index 1 contains the data
  371. builder.add(data[1]);
  372. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  373. var match = ('' + data[1]).match(/^define\("([^"]*)"/);
  374. if (match) {
  375. builder.addId(match[1]);
  376. }
  377. });
  378. // store the generated smalltalk env in self.defaults.smalltalk
  379. builder.finish('self.defaults.smalltalk = smalltalk;');
  380. builder.add('})();');
  381. eval(builder.toString());
  382. console.log('Compiler loaded');
  383. self.defaults.smalltalk.ErrorHandler._setCurrent_(self.defaults.smalltalk.RethrowErrorHandler._new());
  384. if(0 !== self.defaults.jsGlobals.length) {
  385. var jsGlobalVariables = self.defaults.smalltalk.globalJsVariables;
  386. jsGlobalVariables.push.apply(jsGlobalVariables, self.defaults.jsGlobals);
  387. }
  388. self.compile();
  389. });
  390. compilerFilesArray.forEach(function(file) {
  391. console.log('Loading file: ' + file);
  392. fs.readFile(file, compiler_files.add());
  393. });
  394. };
  395. /**
  396. * Compile all given .st files by importing them.
  397. * Followed by category_export().
  398. */
  399. AmberC.prototype.compile = function() {
  400. console.log('Compiling collected .st files');
  401. // import .st files
  402. var self = this;
  403. var imports = new Combo(function() {
  404. Array.prototype.slice.call(arguments).forEach(function(code) {
  405. if (undefined !== code[0]) {
  406. // get element 0 of code since all return values are stored inside an array by Combo
  407. var importer = self.defaults.smalltalk.Importer._new();
  408. try {
  409. importer._import_(code[0]._stream());
  410. } catch (ex) {
  411. throw new Error("Import error in section:\n" +
  412. importer._lastSection() +
  413. "\n\n" +
  414. "while processing chunk:\n" +
  415. importer._lastChunk() +
  416. "\n\n" +
  417. (ex._messageText && ex._messageText() || ex.message || ex));
  418. }
  419. }
  420. });
  421. self.category_export();
  422. });
  423. this.defaults.compile.forEach(function(stFile) {
  424. var callback = imports.add();
  425. if (/\.st/.test(stFile)) {
  426. console.ambercLog('Importing: ' + stFile);
  427. fs.readFile(stFile, 'utf8', function(err, data) {
  428. if (!err)
  429. callback(data);
  430. else
  431. throw new Error('Could not import: ' + stFile);
  432. });
  433. }
  434. });
  435. always_resolve(imports.add());
  436. };
  437. /**
  438. * Export compiled categories to JavaScript files.
  439. * Followed by verify().
  440. */
  441. AmberC.prototype.category_export = function() {
  442. var defaults = this.defaults;
  443. var self = this;
  444. // export categories as .js
  445. async_map(defaults.compile, function(stFile, callback) {
  446. var category = path.basename(stFile, '.st');
  447. var jsFilePath = defaults.output_dir;
  448. if (undefined === jsFilePath) {
  449. jsFilePath = path.dirname(stFile);
  450. }
  451. var jsFile = category + defaults.suffix_used + '.js';
  452. jsFile = path.join(jsFilePath, jsFile);
  453. defaults.compiled.push(jsFile);
  454. var smalltalk = defaults.smalltalk;
  455. var packageObject = smalltalk.Package._named_(category);
  456. packageObject._transport()._namespace_(defaults.amd_namespace);
  457. fs.writeFile(jsFile, smalltalk.String._streamContents_(function (stream) {
  458. smalltalk.AmdExporter._new()._exportPackage_on_(packageObject, stream); }), function(err) {
  459. callback(null, null);
  460. });
  461. }, function(err, result){
  462. self.verify();
  463. });
  464. };
  465. /**
  466. * Verify if all .st files have been compiled.
  467. * Followed by compose_js_files().
  468. */
  469. AmberC.prototype.verify = function() {
  470. console.log('Verifying if all .st files were compiled');
  471. var self = this;
  472. // copy array
  473. var compiledFiles = this.defaults.compiled.slice(0);
  474. async_map(compiledFiles,
  475. function(file, callback) {
  476. fs.exists(file, function(exists) {
  477. if (exists)
  478. callback(null, null);
  479. else
  480. throw(new Error('Compilation failed of: ' + file));
  481. });
  482. }, function(err, result) {
  483. self.compose_js_files();
  484. });
  485. };
  486. /**
  487. * Synchronous function.
  488. * Concatenates compiled JavaScript files into one file in the correct order.
  489. * The name of the produced file is given by defaults.program (set by the last commandline option).
  490. */
  491. AmberC.prototype.compose_js_files = function() {
  492. var defaults = this.defaults;
  493. var programFile = defaults.program;
  494. if (undefined === programFile) {
  495. return;
  496. }
  497. if (undefined !== defaults.output_dir) {
  498. programFile = path.join(defaults.output_dir, programFile);
  499. }
  500. var program_files = [];
  501. if (0 !== defaults.libraries.length) {
  502. console.log('Collecting libraries: ' + defaults.libraries);
  503. program_files.push.apply(program_files, defaults.libraries);
  504. }
  505. if (0 !== defaults.compiled.length) {
  506. var compiledFiles = defaults.compiled.slice(0);
  507. console.log('Collecting compiled files: ' + compiledFiles);
  508. program_files.push.apply(program_files, compiledFiles);
  509. }
  510. console.ambercLog('Writing program file: %s.js', programFile);
  511. var fileStream = fs.createWriteStream(programFile + defaults.suffix_used + '.js');
  512. fileStream.on('error', function(error) {
  513. fileStream.end();
  514. console.ambercLog(error);
  515. });
  516. fileStream.on('close', function(){
  517. return;
  518. });
  519. var builder = createConcatenator();
  520. builder.add('#!/usr/bin/env node');
  521. builder.start();
  522. program_files.forEach(function(file) {
  523. if(fs.existsSync(file)) {
  524. console.log('Adding : ' + file);
  525. var buffer = fs.readFileSync(file);
  526. // matches and returns the "module_id" string in the AMD define: define("module_id", ...)
  527. var match = buffer.toString().match(/^define\("([^"]*)"/);
  528. if (match /*&& match[1].slice(0,9) !== "amber_vm/"*/) {
  529. builder.addId(match[1]);
  530. }
  531. builder.add(buffer);
  532. } else {
  533. fileStream.end();
  534. throw(new Error('Can not find file ' + file));
  535. }
  536. });
  537. var mainFunctionOrFile = '';
  538. if (undefined !== defaults.main) {
  539. console.log('Adding call to: %s>>main', defaults.main);
  540. mainFunctionOrFile += 'smalltalk.' + defaults.main + '._main();';
  541. }
  542. if (undefined !== defaults.mainfile && fs.existsSync(defaults.mainfile)) {
  543. console.log('Adding main file: ' + defaults.mainfile);
  544. mainFunctionOrFile += '\n' + fs.readFileSync(defaults.mainfile);
  545. }
  546. builder.finish(mainFunctionOrFile);
  547. console.log('Writing...');
  548. builder.forEach(function (element) {
  549. fileStream.write(element);
  550. fileStream.write('\n');
  551. });
  552. console.log('Done.');
  553. fileStream.end();
  554. };
  555. module.exports.Compiler = AmberC;
  556. module.exports.createDefaults = createDefaults;
  557. module.exports.Combo = Combo;
  558. module.exports.map = async_map;