1
0

amberc.js 16 KB

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