amberc.js 17 KB

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