1
0

amberc.js 17 KB

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