amberc.js 18 KB

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