amberc.js 18 KB

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