1
0

amberc.js 18 KB

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