1
0

amberc.js 18 KB

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