1
0

amberc.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. self.create_compiler(resolved_compiler_files[0]);
  292. });
  293. this.resolve_kernel(all_resolved.add());
  294. this.resolve_compiler(all_resolved.add());
  295. };
  296. /**
  297. * Resolve .js files needed by kernel
  298. * callback is evaluated afterwards.
  299. */
  300. AmberC.prototype.resolve_kernel = function(callback) {
  301. var self = this;
  302. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  303. var kernel_resolved = new Combo(function() {
  304. var foundLibraries = [];
  305. Array.prototype.slice.call(arguments).forEach(function(file) {
  306. if (undefined !== file[0]) {
  307. foundLibraries.push(file[0]);
  308. }
  309. });
  310. // boot.js and Kernel files need to be used first
  311. // otherwise the global smalltalk object is undefined
  312. self.defaults.libraries = foundLibraries.concat(self.defaults.libraries);
  313. callback(null);
  314. });
  315. kernel_files.forEach(function(file) {
  316. self.resolve_js(file, kernel_resolved.add());
  317. });
  318. always_resolve(kernel_resolved.add());
  319. };
  320. /**
  321. * Resolve .js files needed by compiler.
  322. * callback is evaluated afterwards with resolved files as argument.
  323. */
  324. AmberC.prototype.resolve_compiler = function(callback) {
  325. // Resolve compiler libraries
  326. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  327. var compiler_resolved = new Combo(function() {
  328. var compilerFiles = [];
  329. Array.prototype.slice.call(arguments).forEach(function(file) {
  330. if (undefined !== file[0]) {
  331. compilerFiles.push(file[0]);
  332. }
  333. });
  334. callback(compilerFiles);
  335. });
  336. var self = this;
  337. compiler_files.forEach(function(file) {
  338. self.resolve_js(file, compiler_resolved.add());
  339. });
  340. always_resolve(compiler_resolved.add());
  341. };
  342. /**
  343. * Read all .js files needed by compiler and eval() them.
  344. * The finished Compiler gets stored in defaults.smalltalk.
  345. * Followed by compile().
  346. */
  347. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  348. var self = this;
  349. var compiler_files = new Combo(function() {
  350. var builder = createConcatenator();
  351. builder.add('(function() {');
  352. builder.start();
  353. Array.prototype.slice.call(arguments).forEach(function(data) {
  354. // data is an array where index 0 is the error code and index 1 contains the data
  355. builder.add(data[1]);
  356. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  357. var match = ('' + data[1]).match(/^define\("([^"]*)"/);
  358. if (match) {
  359. builder.addId(match[1]);
  360. }
  361. });
  362. // store the generated smalltalk env in self.defaults.smalltalk
  363. builder.finish('self.defaults.smalltalk = smalltalk;');
  364. builder.add('})();');
  365. eval(builder.toString());
  366. console.log('Compiler loaded');
  367. self.defaults.smalltalk.ErrorHandler._setCurrent_(self.defaults.smalltalk.RethrowErrorHandler._new());
  368. if(0 !== self.defaults.jsGlobals.length) {
  369. var jsGlobalVariables = self.defaults.smalltalk.globalJsVariables;
  370. jsGlobalVariables.push.apply(jsGlobalVariables, self.defaults.jsGlobals);
  371. }
  372. readFiles(self.defaults).then(compile(self.defaults)
  373. , function(error) {
  374. console.error(error);
  375. }).then(function() {
  376. return self.defaults;
  377. }).then(category_export)
  378. .then(function(resolve) {
  379. return self.defaults;
  380. }, function(error) {
  381. console.error(error);
  382. }).then(verify)
  383. .then(function(resolve) {
  384. return self.defaults;
  385. }, function(error) {
  386. console.error(error);
  387. }).then(compose_js_files);
  388. });
  389. compilerFilesArray.forEach(function(file) {
  390. console.log('Loading file: ' + file);
  391. fs.readFile(file, compiler_files.add());
  392. });
  393. };
  394. /**
  395. * Compile all given .st files by importing them.
  396. * Captures the configuration object in a closure and returns a function that
  397. * does the actual work and returns a Promise.all() object.
  398. */
  399. function compile(configuration) {
  400. // return function which does the actual work
  401. // and use the compile function to reference the configuration object
  402. return function (fileContents) {
  403. console.log('Compiling collected .st files');
  404. // import/compile content of .st files
  405. return Promise.all(
  406. fileContents.map(function(code) {
  407. return new Promise(function(resolve, error) {
  408. var importer = configuration.smalltalk.Importer._new();
  409. try {
  410. importer._import_(code._stream());
  411. resolve(true);
  412. } catch (ex) {
  413. error(Error("Import error in section:\n" +
  414. importer._lastSection() + "\n\n" +
  415. "while processing chunk:\n" +
  416. importer._lastChunk() + "\n\n" +
  417. (ex._messageText && ex._messageText() || ex.message || ex))
  418. );
  419. }
  420. });
  421. })
  422. );
  423. };
  424. };
  425. /**
  426. * Read the content of all files into memory.
  427. * Returns a Promise.all() object.
  428. */
  429. function readFiles(configuration) {
  430. return Promise.all(
  431. configuration.compile.map(function(stFile) {
  432. return new Promise(function(resolve, error) {
  433. if (/\.st/.test(stFile)) {
  434. console.ambercLog('Importing: ' + stFile);
  435. fs.readFile(stFile, 'utf8', function(err, data) {
  436. if (!err)
  437. resolve(data);
  438. else
  439. error(Error('Could not import: ' + stFile));
  440. });
  441. }
  442. });
  443. })
  444. );
  445. };
  446. /**
  447. * Export compiled categories to JavaScript files.
  448. * Returns a Promise.all() object.
  449. */
  450. function category_export(configuration) {
  451. return Promise.all(
  452. configuration.compile.map(function(stFile) {
  453. return new Promise(function(resolve, error) {
  454. var category = path.basename(stFile, '.st');
  455. var jsFilePath = configuration.output_dir;
  456. if (undefined === jsFilePath) {
  457. jsFilePath = path.dirname(stFile);
  458. }
  459. var jsFile = category + configuration.suffix_used + '.js';
  460. jsFile = path.join(jsFilePath, jsFile);
  461. configuration.compiled.push(jsFile);
  462. var smalltalk = configuration.smalltalk;
  463. var packageObject = smalltalk.Package._named_(category);
  464. packageObject._transport()._namespace_(configuration.amd_namespace);
  465. fs.writeFile(jsFile, smalltalk.String._streamContents_(function (stream) {
  466. smalltalk.AmdExporter._new()._exportPackage_on_(packageObject, stream);
  467. }), function(err) {
  468. if (err)
  469. error(err);
  470. else
  471. resolve(true);
  472. });
  473. });
  474. })
  475. );
  476. };
  477. /**
  478. * Verify if all .st files have been compiled.
  479. * Returns a Promise.all() object.
  480. */
  481. function verify(configuration) {
  482. console.log('Verifying if all .st files were compiled');
  483. return Promise.all(
  484. configuration.compiled.map(function(file) {
  485. return new Promise(function(resolve, error) {
  486. fs.exists(file, function(exists) {
  487. if (exists)
  488. resolve(true);
  489. else
  490. error(Error('Compilation failed of: ' + file));
  491. });
  492. });
  493. })
  494. );
  495. };
  496. /**
  497. * Synchronous function.
  498. * Concatenates compiled JavaScript files into one file in the correct order.
  499. * The name of the produced file is given by configuration.program (set by the last commandline option).
  500. * Returns a Promise.
  501. */
  502. function compose_js_files(configuration) {
  503. return new Promise(function(resolve, reject) {
  504. var defaults = configuration;
  505. var programFile = defaults.program;
  506. if (undefined === programFile) {
  507. return;
  508. }
  509. if (undefined !== defaults.output_dir) {
  510. programFile = path.join(defaults.output_dir, programFile);
  511. }
  512. var program_files = [];
  513. if (0 !== defaults.libraries.length) {
  514. console.log('Collecting libraries: ' + defaults.libraries);
  515. program_files.push.apply(program_files, defaults.libraries);
  516. }
  517. if (0 !== defaults.compiled.length) {
  518. var compiledFiles = defaults.compiled.slice(0);
  519. console.log('Collecting compiled files: ' + compiledFiles);
  520. program_files.push.apply(program_files, compiledFiles);
  521. }
  522. console.ambercLog('Writing program file: %s.js', programFile);
  523. var fileStream = fs.createWriteStream(programFile + defaults.suffix_used + '.js');
  524. fileStream.on('error', function(error) {
  525. fileStream.end();
  526. console.ambercLog(error);
  527. });
  528. fileStream.on('close', function(){
  529. return;
  530. });
  531. var builder = createConcatenator();
  532. builder.add('#!/usr/bin/env node');
  533. builder.start();
  534. program_files.forEach(function(file) {
  535. if(fs.existsSync(file)) {
  536. console.log('Adding : ' + file);
  537. var buffer = fs.readFileSync(file);
  538. // matches and returns the "module_id" string in the AMD define: define("module_id", ...)
  539. var match = buffer.toString().match(/^define\("([^"]*)"/);
  540. if (match /*&& match[1].slice(0,9) !== "amber_vm/"*/) {
  541. builder.addId(match[1]);
  542. }
  543. builder.add(buffer);
  544. } else {
  545. fileStream.end();
  546. throw(new Error('Can not find file ' + file));
  547. }
  548. });
  549. var mainFunctionOrFile = '';
  550. if (undefined !== defaults.main) {
  551. console.log('Adding call to: %s>>main', defaults.main);
  552. mainFunctionOrFile += 'smalltalk.' + defaults.main + '._main();';
  553. }
  554. if (undefined !== defaults.mainfile && fs.existsSync(defaults.mainfile)) {
  555. console.log('Adding main file: ' + defaults.mainfile);
  556. mainFunctionOrFile += '\n' + fs.readFileSync(defaults.mainfile);
  557. }
  558. builder.finish(mainFunctionOrFile);
  559. console.log('Writing...');
  560. builder.forEach(function (element) {
  561. fileStream.write(element);
  562. fileStream.write('\n');
  563. });
  564. console.log('Done.');
  565. fileStream.end();
  566. resolve(true);
  567. });
  568. };
  569. module.exports.Compiler = AmberC;
  570. module.exports.createDefaults = createDefaults;
  571. module.exports.Combo = Combo;