1
0

amberc.js 17 KB

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