1
0

amberc.js 18 KB

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