1
0

amberc.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 all compilation steps get triggered.
  106. */
  107. AmberC.prototype.main = function(configuration, finished_callback) {
  108. console.time('Compile Time');
  109. if (undefined !== finished_callback) {
  110. configuration.finished_callback = finished_callback;
  111. }
  112. if (configuration.amd_namespace.length === 0) {
  113. configuration.amd_namespace = 'amber_core';
  114. }
  115. if (undefined !== configuration.jsLibraryDirs) {
  116. configuration.jsLibraryDirs.push(path.join(this.amber_dir, 'js'));
  117. configuration.jsLibraryDirs.push(path.join(this.amber_dir, 'support'));
  118. }
  119. console.ambercLog = console.log;
  120. if (false === configuration.verbose) {
  121. console.log = function() {};
  122. }
  123. var self = this;
  124. check_configuration(configuration).then(function(configuration) {
  125. configuration.smalltalk = {}; // the evaluated compiler will be stored in this variable (see create_compiler)
  126. configuration.kernel_libraries = self.kernel_libraries;
  127. configuration.compiler_libraries = self.compiler_libraries;
  128. configuration.amber_dir = self.amber_dir;
  129. return configuration;
  130. }, function (error) {
  131. console.log(error);
  132. })
  133. .then(collect_st_files)
  134. .then(collect_js_files)
  135. .then(resolve_kernel)
  136. .then(resolve_compiler)
  137. .then(create_compiler(configuration))
  138. .then(function(resolve) {
  139. return configuration;
  140. })
  141. .then(readFiles)
  142. .then(compile(configuration), function(error) {
  143. console.error(error);
  144. })
  145. .then(function() {
  146. return configuration;
  147. })
  148. .then(category_export)
  149. .then(function(resolve) {
  150. return configuration;
  151. }, function(error) {
  152. console.error(error);
  153. })
  154. .then(verify)
  155. .then(function(resolve) {
  156. return configuration;
  157. }, function(error) {
  158. console.error(error);
  159. })
  160. .then(compose_js_files)
  161. .then(function() {
  162. console.log = console.ambercLog;
  163. console.timeEnd('Compile Time');
  164. });
  165. };
  166. /**
  167. * Check if the passed in configuration object has sufficient/nonconflicting values.
  168. * Calls reject with an Error object upon failure and resolve(configuration) upon success.
  169. */
  170. function check_configuration(configuration) {
  171. return new Promise(function(resolve, reject) {
  172. if (undefined === configuration) {
  173. reject(Error('AmberC.check_configuration_ok(): missing configuration object'));
  174. }
  175. if (0 === configuration.jsFiles.length && 0 === configuration.stFiles.length) {
  176. reject(Error('AmberC.check_configuration_ok(): no files to compile/link specified in configuration object'));
  177. }
  178. resolve(configuration);
  179. });
  180. };
  181. /**
  182. * Check if the file given as parameter exists in any of the following directories:
  183. * 1. current local directory
  184. * 2. defauls.jsLibraryDirs
  185. * 3. $AMBER/js/
  186. * 3. $AMBER/support/
  187. *
  188. * @param filename name of a file without '.js' prefix
  189. * @param callback gets called on success with path to .js file as parameter
  190. */
  191. function resolve_js(filename, configuration, callback) {
  192. var baseName = path.basename(filename, '.js');
  193. var jsFile = baseName + configuration.loadsuffix + '.js';
  194. console.log('Resolving: ' + jsFile);
  195. fs.exists(jsFile, function(exists) {
  196. if (exists) {
  197. callback(jsFile);
  198. } else {
  199. var amberJsFile = '';
  200. // check for specified .js file in any of the directories from jsLibraryDirs
  201. var found = configuration.jsLibraryDirs.some(function(directory) {
  202. amberJsFile = path.join(directory, jsFile);
  203. return fs.existsSync(amberJsFile);
  204. });
  205. if (found) {
  206. callback(amberJsFile);
  207. } else {
  208. throw(new Error('JavaScript file not found: ' + jsFile));
  209. }
  210. }
  211. });
  212. };
  213. /**
  214. * Resolve st files given by stFiles and add them to defaults.compile.
  215. * Returns a Promise which resolves to configuration.
  216. */
  217. function collect_st_files(configuration) {
  218. return new Promise(function(resolve, error) {
  219. Promise.all(
  220. configuration.stFiles.map(function(stFile) {
  221. return new Promise(function(resolve, error) {
  222. console.log('Checking: ' + stFile);
  223. var amberStFile = path.join(configuration.amber_dir, 'st', stFile);
  224. fs.exists(stFile, function(exists) {
  225. if (exists) {
  226. resolve(stFile);
  227. } else {
  228. console.log('Checking: ' + amberStFile);
  229. fs.exists(amberStFile, function(exists) {
  230. if (exists) {
  231. resolve(amberStFile);
  232. } else {
  233. error(Error('Smalltalk file not found: ' + amberStFile));
  234. }
  235. });
  236. }
  237. });
  238. });
  239. })
  240. ).then(function(data) {
  241. configuration.compile = configuration.compile.concat(data);
  242. resolve(configuration);
  243. }, function(error) {
  244. error(error);
  245. });
  246. });
  247. };
  248. /**
  249. * Resolve js files given by jsFiles and add them to configuration.libraries.
  250. * Returns a Promise which resolves with configuration.
  251. */
  252. function collect_js_files(configuration) {
  253. return new Promise(function(resolve, error) {
  254. Promise.all(
  255. configuration.jsFiles.map(function(file) {
  256. return new Promise(function(resolve, error) {
  257. resolve_js(file, configuration, resolve);
  258. });
  259. })
  260. ).then(function(data) {
  261. configuration.libraries = configuration.libraries.concat(data);
  262. resolve(configuration);
  263. }, function(error) {
  264. error(error);
  265. });
  266. });
  267. };
  268. /**
  269. * Resolve .js files needed by kernel.
  270. * Returns a Promise which resolves with the configuration object.
  271. */
  272. function resolve_kernel(configuration) {
  273. var kernel_files = configuration.kernel_libraries.concat(configuration.load);
  274. return new Promise(function(resolve, error) {
  275. Promise.all(
  276. kernel_files.map(function(file) {
  277. return new Promise(function(resolve, error) {
  278. resolve_js(file, configuration, resolve);
  279. });
  280. })
  281. ).then(function(data) {
  282. // boot.js and Kernel files need to be used first
  283. // otherwise the global smalltalk object is undefined
  284. configuration.libraries = data.concat(configuration.libraries);
  285. resolve(configuration);
  286. }, function(error) {
  287. error(error);
  288. });
  289. });
  290. };
  291. /**
  292. * Resolve .js files needed by compiler.
  293. * Returns a Promise which resolves with an array of all compiler related files.
  294. */
  295. function resolve_compiler(configuration) {
  296. // Resolve compiler libraries
  297. var compiler_files = configuration.compiler_libraries.concat(configuration.load);
  298. return new Promise(function(resolve, error) {
  299. Promise.all(
  300. compiler_files.map(function(file) {
  301. return new Promise(function(resolve, error) {
  302. resolve_js(file, configuration, resolve);
  303. });
  304. })
  305. ).then(function(compilerFiles) {
  306. resolve(compilerFiles);
  307. }, function(error) {
  308. error(error);
  309. });
  310. });
  311. };
  312. /**
  313. * Read all .js files needed by compiler and eval() them.
  314. * The finished Compiler gets stored in configuration.smalltalk.
  315. * Returns a Promise object.
  316. */
  317. function create_compiler(configuration) {
  318. return function(compilerFilesArray) {
  319. return new Promise(function(resolve, error) {
  320. Promise.all(
  321. compilerFilesArray.map(function(file) {
  322. return new Promise(function(resolve, error) {
  323. console.log('Loading file: ' + file);
  324. fs.readFile(file, function(err, data) {
  325. if (err)
  326. error(err);
  327. else
  328. resolve(data);
  329. });
  330. });
  331. })
  332. ).then(function(files) {
  333. var builder = createConcatenator();
  334. builder.add('(function() {');
  335. builder.start();
  336. files.forEach(function(data) {
  337. // data is an array where index 0 is the error code and index 1 contains the data
  338. builder.add(data);
  339. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  340. var match = ('' + data).match(/^define\("([^"]*)"/);
  341. if (match) {
  342. builder.addId(match[1]);
  343. }
  344. });
  345. // store the generated smalltalk env in self.defaults.smalltalk
  346. builder.finish('configuration.smalltalk = smalltalk;');
  347. builder.add('})();');
  348. eval(builder.toString());
  349. console.log('Compiler loaded');
  350. configuration.smalltalk.ErrorHandler._setCurrent_(configuration.smalltalk.RethrowErrorHandler._new());
  351. if(0 !== configuration.jsGlobals.length) {
  352. var jsGlobalVariables = configuration.smalltalk.globalJsVariables;
  353. jsGlobalVariables.push.apply(jsGlobalVariables, configuration.jsGlobals);
  354. }
  355. resolve(true);
  356. }, function(error) {
  357. error(Error('Error creating compiler'));
  358. });
  359. });
  360. };
  361. };
  362. /**
  363. * Compile all given .st files by importing them.
  364. * Captures the configuration object in a closure and returns a function that
  365. * does the actual work and returns a Promise.all() object.
  366. */
  367. function compile(configuration) {
  368. // return function which does the actual work
  369. // and use the compile function to reference the configuration object
  370. return function(fileContents) {
  371. console.log('Compiling collected .st files');
  372. // import/compile content of .st files
  373. return Promise.all(
  374. fileContents.map(function(code) {
  375. return new Promise(function(resolve, error) {
  376. var importer = configuration.smalltalk.Importer._new();
  377. try {
  378. importer._import_(code._stream());
  379. resolve(true);
  380. } catch (ex) {
  381. error(Error("Import error in section:\n" +
  382. importer._lastSection() + "\n\n" +
  383. "while processing chunk:\n" +
  384. importer._lastChunk() + "\n\n" +
  385. (ex._messageText && ex._messageText() || ex.message || ex))
  386. );
  387. }
  388. });
  389. })
  390. );
  391. };
  392. };
  393. /**
  394. * Read the content of all files into memory.
  395. * Returns a Promise.all() object.
  396. */
  397. function readFiles(configuration) {
  398. return Promise.all(
  399. configuration.compile.map(function(stFile) {
  400. return new Promise(function(resolve, error) {
  401. if (/\.st/.test(stFile)) {
  402. console.ambercLog('Importing: ' + stFile);
  403. fs.readFile(stFile, 'utf8', function(err, data) {
  404. if (!err)
  405. resolve(data);
  406. else
  407. error(Error('Could not import: ' + stFile));
  408. });
  409. }
  410. });
  411. })
  412. );
  413. };
  414. /**
  415. * Export compiled categories to JavaScript files.
  416. * Returns a Promise.all() object.
  417. */
  418. function category_export(configuration) {
  419. return Promise.all(
  420. configuration.compile.map(function(stFile) {
  421. return new Promise(function(resolve, error) {
  422. var category = path.basename(stFile, '.st');
  423. var jsFilePath = configuration.output_dir;
  424. if (undefined === jsFilePath) {
  425. jsFilePath = path.dirname(stFile);
  426. }
  427. var jsFile = category + configuration.suffix_used + '.js';
  428. jsFile = path.join(jsFilePath, jsFile);
  429. configuration.compiled.push(jsFile);
  430. var smalltalk = configuration.smalltalk;
  431. var packageObject = smalltalk.Package._named_(category);
  432. packageObject._transport()._namespace_(configuration.amd_namespace);
  433. fs.writeFile(jsFile, smalltalk.String._streamContents_(function (stream) {
  434. smalltalk.AmdExporter._new()._exportPackage_on_(packageObject, stream);
  435. }), function(err) {
  436. if (err)
  437. error(err);
  438. else
  439. resolve(true);
  440. });
  441. });
  442. })
  443. );
  444. };
  445. /**
  446. * Verify if all .st files have been compiled.
  447. * Returns a Promise.all() object.
  448. */
  449. function verify(configuration) {
  450. console.log('Verifying if all .st files were compiled');
  451. return Promise.all(
  452. configuration.compiled.map(function(file) {
  453. return new Promise(function(resolve, error) {
  454. fs.exists(file, function(exists) {
  455. if (exists)
  456. resolve(true);
  457. else
  458. error(Error('Compilation failed of: ' + file));
  459. });
  460. });
  461. })
  462. );
  463. };
  464. /**
  465. * Synchronous function.
  466. * Concatenates compiled JavaScript files into one file in the correct order.
  467. * The name of the produced file is given by configuration.program (set by the last commandline option).
  468. * Returns a Promise.
  469. */
  470. function compose_js_files(configuration) {
  471. return new Promise(function(resolve, reject) {
  472. var defaults = configuration;
  473. var programFile = defaults.program;
  474. if (undefined === programFile) {
  475. return;
  476. }
  477. if (undefined !== defaults.output_dir) {
  478. programFile = path.join(defaults.output_dir, programFile);
  479. }
  480. var program_files = [];
  481. if (0 !== defaults.libraries.length) {
  482. console.log('Collecting libraries: ' + defaults.libraries);
  483. program_files.push.apply(program_files, defaults.libraries);
  484. }
  485. if (0 !== defaults.compiled.length) {
  486. var compiledFiles = defaults.compiled.slice(0);
  487. console.log('Collecting compiled files: ' + compiledFiles);
  488. program_files.push.apply(program_files, compiledFiles);
  489. }
  490. console.ambercLog('Writing program file: %s.js', programFile);
  491. var fileStream = fs.createWriteStream(programFile + defaults.suffix_used + '.js');
  492. fileStream.on('error', function(error) {
  493. fileStream.end();
  494. console.ambercLog(error);
  495. });
  496. fileStream.on('close', function(){
  497. return;
  498. });
  499. var builder = createConcatenator();
  500. builder.add('#!/usr/bin/env node');
  501. builder.start();
  502. program_files.forEach(function(file) {
  503. if(fs.existsSync(file)) {
  504. console.log('Adding : ' + file);
  505. var buffer = fs.readFileSync(file);
  506. // matches and returns the "module_id" string in the AMD define: define("module_id", ...)
  507. var match = buffer.toString().match(/^define\("([^"]*)"/);
  508. if (match /*&& match[1].slice(0,9) !== "amber_vm/"*/) {
  509. builder.addId(match[1]);
  510. }
  511. builder.add(buffer);
  512. } else {
  513. fileStream.end();
  514. throw(new Error('Can not find file ' + file));
  515. }
  516. });
  517. var mainFunctionOrFile = '';
  518. if (undefined !== defaults.main) {
  519. console.log('Adding call to: %s>>main', defaults.main);
  520. mainFunctionOrFile += 'smalltalk.' + defaults.main + '._main();';
  521. }
  522. if (undefined !== defaults.mainfile && fs.existsSync(defaults.mainfile)) {
  523. console.log('Adding main file: ' + defaults.mainfile);
  524. mainFunctionOrFile += '\n' + fs.readFileSync(defaults.mainfile);
  525. }
  526. builder.finish(mainFunctionOrFile);
  527. console.log('Writing...');
  528. builder.forEach(function (element) {
  529. fileStream.write(element);
  530. fileStream.write('\n');
  531. });
  532. console.log('Done.');
  533. fileStream.end();
  534. resolve(true);
  535. });
  536. };
  537. module.exports.Compiler = AmberC;
  538. module.exports.createDefaults = createDefaults;