amberc.js 17 KB

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