amberc.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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', ['/optional/path/to/compiler.jar]);
  6. * compiler.main();
  7. *
  8. * Execute 'node compiler.js' without arguments or with -h / --help for help.
  9. */
  10. /**
  11. * Map the async filter function onto array and evaluate callback, once all have finished.
  12. * Taken from: http://howtonode.org/control-flow-part-iii
  13. */
  14. function async_map(array, filter, callback) {
  15. if (0 === array.length) {
  16. callback(null, null);
  17. return;
  18. }
  19. var counter = array.length;
  20. var new_array = [];
  21. array.forEach(function (item, index) {
  22. filter(item, function (err, result) {
  23. if (err) { callback(err); return; }
  24. new_array[index] = result;
  25. counter--;
  26. if (counter === 0) {
  27. callback(null, new_array);
  28. }
  29. });
  30. });
  31. }
  32. /**
  33. * Always evaluates the callback parameter.
  34. * Used by Combo blocks to always call the next function,
  35. * even if all of the other functions did not run.
  36. */
  37. function always_resolve(callback) {
  38. callback();
  39. }
  40. /**
  41. * Helper for concatenating Amber generated AMD modules.
  42. * The produced output can be exported and run as an independent program.
  43. *
  44. * var concatenator = createConcatenator();
  45. * concatenator.start(); // write the required AMD define header
  46. * concatenator.add(module1);
  47. * concatenator.addId(module1_ID);
  48. * //...
  49. * concatenator.finish("//some last code");
  50. * var concatenation = concatenator.toString();
  51. * // The variable concatenation contains the concatenated result
  52. * // which can either be stored in a file or interpreted with eval().
  53. */
  54. function createConcatenator () {
  55. return {
  56. elements: [],
  57. ids: [],
  58. add: function () {
  59. this.elements.push.apply(this.elements, arguments);
  60. },
  61. addId: function () {
  62. this.ids.push.apply(this.ids, arguments);
  63. },
  64. forEach: function () {
  65. this.elements.forEach.apply(this.elements, arguments);
  66. },
  67. start: function () {
  68. this.add(
  69. 'var define = (' + require('amdefine') + ')(), requirejs = define.require;',
  70. 'define("amber_vm/browser-compatibility", [], {});'
  71. );
  72. },
  73. finish: function (realWork) {
  74. this.add(
  75. 'define("amber_vm/_init", ["amber_vm/smalltalk","' + this.ids.join('","') + '"], function (smalltalk) {',
  76. 'smalltalk.initialize();',
  77. realWork,
  78. '});',
  79. 'requirejs("amber_vm/_init");'
  80. );
  81. },
  82. toString: function () {
  83. return this.elements.join('\n');
  84. }
  85. };
  86. }
  87. /**
  88. * Combine several async functions and evaluate callback once all of them have finished.
  89. * Taken from: http://howtonode.org/control-flow
  90. */
  91. function Combo(callback) {
  92. this.callback = callback;
  93. this.items = 0;
  94. this.results = [];
  95. }
  96. Combo.prototype = {
  97. add: function () {
  98. var self = this,
  99. id = this.items;
  100. this.items++;
  101. return function () {
  102. self.check(id, arguments);
  103. };
  104. },
  105. check: function (id, arguments) {
  106. this.results[id] = Array.prototype.slice.call(arguments);
  107. this.items--;
  108. if (this.items == 0) {
  109. this.callback.apply(this, this.results);
  110. }
  111. }
  112. };
  113. var path = require('path'),
  114. util = require('util'),
  115. fs = require('fs'),
  116. exec = require('child_process').exec;
  117. /**
  118. * AmberC constructor function.
  119. * amber_dir: points to the location of an amber installation
  120. * closure_jar: location of compiler.jar (can be left undefined)
  121. */
  122. function AmberC(amber_dir) {
  123. if (undefined === amber_dir || !fs.existsSync(amber_dir)) {
  124. throw new Error('amber_dir needs to be a valid directory');
  125. }
  126. this.amber_dir = amber_dir;
  127. this.kernel_libraries = ['@boot', '@smalltalk', '@nil', '@_st', 'Kernel-Objects', 'Kernel-Classes', 'Kernel-Methods',
  128. 'Kernel-Collections', 'Kernel-Infrastructure', 'Kernel-Exceptions', 'Kernel-Transcript',
  129. 'Kernel-Announcements'];
  130. this.compiler_libraries = this.kernel_libraries.concat(['@parser', 'Importer-Exporter', 'Compiler-Exceptions',
  131. 'Compiler-Core', 'Compiler-AST', 'Compiler-Exceptions', 'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic']);
  132. }
  133. /**
  134. * Default values.
  135. */
  136. var createDefaults = function(amber_dir, finished_callback){
  137. return {
  138. 'load': [],
  139. 'main': undefined,
  140. 'mainfile': undefined,
  141. 'stFiles': [],
  142. 'jsFiles': [],
  143. 'jsGlobals': [],
  144. 'amd_namespace': 'amber_core',
  145. 'suffix': '',
  146. 'loadsuffix': '',
  147. 'suffix_used': '',
  148. 'libraries': [],
  149. 'jsLibraryDirs': [],
  150. 'compile': [],
  151. 'compiled': [],
  152. 'program': undefined,
  153. 'output_dir': undefined,
  154. 'verbose': false,
  155. 'finished_callback': finished_callback
  156. };
  157. };
  158. /**
  159. * Main function for executing the compiler.
  160. * If check_configuration_ok() returns successfully the configuration is set on the current compiler
  161. * instance and check_for_closure_compiler() gets called.
  162. * The last step is to call collect_files().
  163. */
  164. AmberC.prototype.main = function(configuration, finished_callback) {
  165. console.time('Compile Time');
  166. if (undefined !== finished_callback) {
  167. configuration.finished_callback = finished_callback;
  168. }
  169. if (configuration.amd_namespace.length == 0) {
  170. configuration.amd_namespace = 'amber_core';
  171. }
  172. if (undefined !== configuration.jsLibraryDirs) {
  173. configuration.jsLibraryDirs.push(this.amber_dir);
  174. }
  175. console.ambercLog = console.log;
  176. if (false === configuration.verbose) {
  177. console.log = function() {};
  178. }
  179. if (this.check_configuration_ok(configuration)) {
  180. this.defaults = configuration;
  181. this.defaults.smalltalk = {}; // the evaluated compiler will be stored in this variable (see create_compiler)
  182. this.collect_files(this.defaults.stFiles, this.defaults.jsFiles)
  183. }
  184. };
  185. /**
  186. * Check if the passed in configuration object has sufficient/nonconflicting values
  187. */
  188. AmberC.prototype.check_configuration_ok = function(configuration) {
  189. if (undefined === configuration) {
  190. throw new Error('AmberC.check_configuration_ok(): missing configuration object');
  191. }
  192. if (0 === configuration.jsFiles.length && 0 === configuration.stFiles.lenght) {
  193. throw new Error('AmberC.check_configuration_ok(): no files to compile/link specified in configuration object');
  194. }
  195. return true;
  196. };
  197. /**
  198. * Check if the file given as parameter exists in the local directory or in $AMBER/js/.
  199. * '.js' is appended first.
  200. *
  201. * @param filename name of a file without '.js' prefix
  202. * @param callback gets called on success with path to .js file as parameter
  203. */
  204. AmberC.prototype.resolve_js = function(filename, callback) {
  205. var special = filename[0] == "@";
  206. if (special) {
  207. filename = filename.slice(1);
  208. }
  209. var baseName = path.basename(filename, '.js');
  210. var jsFile = baseName + this.defaults.loadsuffix + '.js';
  211. var defaults = this.defaults;
  212. console.log('Resolving: ' + jsFile);
  213. fs.exists(jsFile, function(exists) {
  214. if (exists) {
  215. callback(jsFile);
  216. } else {
  217. var amberJsFile = '';
  218. // check for specified .js file in any of the directories from jsLibraryDirs
  219. var notFound = defaults.jsLibraryDirs.every(function(directory) {
  220. amberJsFile = path.join(directory, special?'support':'js', jsFile);
  221. if (fs.existsSync(amberJsFile)) {
  222. return false;
  223. }
  224. return true;
  225. });
  226. if (notFound) {
  227. throw(new Error('JavaScript file not found: ' + jsFile));
  228. } else {
  229. callback(amberJsFile);
  230. }
  231. }
  232. });
  233. };
  234. /**
  235. * Collect libraries and Smalltalk files looking
  236. * both locally and in $AMBER/js and $AMBER/st.
  237. * Followed by resolve_libraries().
  238. */
  239. AmberC.prototype.collect_files = function(stFiles, jsFiles) {
  240. var self = this;
  241. var collected_files = new Combo(function() {
  242. self.resolve_libraries();
  243. });
  244. if (0 !== stFiles.length) {
  245. self.collect_st_files(stFiles, collected_files.add());
  246. }
  247. if (0 !== jsFiles.length) {
  248. self.collect_js_files(jsFiles, collected_files.add());
  249. }
  250. };
  251. /**
  252. * Resolve st files given by stFiles and add them to defaults.compile.
  253. * Respective categories get added to defaults.compile_categories.
  254. * callback is evaluated afterwards.
  255. */
  256. AmberC.prototype.collect_st_files = function(stFiles, callback) {
  257. var defaults = this.defaults;
  258. var self = this;
  259. var collected_st_files = new Combo(function() {
  260. Array.prototype.slice.call(arguments).forEach(function(data) {
  261. var stFile = data[0];
  262. defaults.compile.push(stFile);
  263. });
  264. callback();
  265. });
  266. stFiles.forEach(function(stFile) {
  267. var _callback = collected_st_files.add();
  268. console.log('Checking: ' + stFile);
  269. var amberStFile = path.join(self.amber_dir, 'st', stFile);
  270. fs.exists(stFile, function(exists) {
  271. if (exists) {
  272. _callback(stFile);
  273. } else {
  274. console.log('Checking: ' + amberStFile);
  275. fs.exists(amberStFile, function(exists) {
  276. if (exists) {
  277. _callback(amberStFile);
  278. } else {
  279. throw(new Error('Smalltalk file not found: ' + amberStFile));
  280. }
  281. });
  282. }
  283. });
  284. });
  285. };
  286. /**
  287. * Resolve js files given by jsFiles and add them to defaults.libraries.
  288. * callback is evaluated afterwards.
  289. */
  290. AmberC.prototype.collect_js_files = function(jsFiles, callback) {
  291. var self = this;
  292. var collected_js_files = new Combo(function() {
  293. Array.prototype.slice.call(arguments).forEach(function(file) {
  294. self.defaults.libraries.push(file[0]);
  295. });
  296. callback();
  297. });
  298. jsFiles.forEach(function(jsFile) {
  299. self.resolve_js(jsFile, collected_js_files.add());
  300. });
  301. };
  302. /**
  303. * Resolve kernel and compiler files.
  304. * Followed by resolve_init().
  305. */
  306. AmberC.prototype.resolve_libraries = function() {
  307. // Resolve libraries listed in this.kernel_libraries
  308. var self = this;
  309. var all_resolved = new Combo(function(resolved_kernel_files, resolved_compiler_files) {
  310. self.create_compiler(resolved_compiler_files[0]);
  311. });
  312. this.resolve_kernel(all_resolved.add());
  313. this.resolve_compiler(all_resolved.add());
  314. };
  315. /**
  316. * Resolve .js files needed by kernel
  317. * callback is evaluated afterwards.
  318. */
  319. AmberC.prototype.resolve_kernel = function(callback) {
  320. var self = this;
  321. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  322. var kernel_resolved = new Combo(function() {
  323. var foundLibraries = [];
  324. Array.prototype.slice.call(arguments).forEach(function(file) {
  325. if (undefined !== file[0]) {
  326. foundLibraries.push(file[0]);
  327. }
  328. });
  329. // boot.js and Kernel files need to be used first
  330. // otherwise the global smalltalk object is undefined
  331. self.defaults.libraries = foundLibraries.concat(self.defaults.libraries);
  332. callback(null);
  333. });
  334. kernel_files.forEach(function(file) {
  335. self.resolve_js(file, kernel_resolved.add());
  336. });
  337. always_resolve(kernel_resolved.add());
  338. };
  339. /**
  340. * Resolve .js files needed by compiler.
  341. * callback is evaluated afterwards with resolved files as argument.
  342. */
  343. AmberC.prototype.resolve_compiler = function(callback) {
  344. // Resolve compiler libraries
  345. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  346. var compiler_resolved = new Combo(function() {
  347. var compilerFiles = [];
  348. Array.prototype.slice.call(arguments).forEach(function(file) {
  349. if (undefined !== file[0]) {
  350. compilerFiles.push(file[0]);
  351. }
  352. });
  353. callback(compilerFiles);
  354. });
  355. var self = this
  356. compiler_files.forEach(function(file) {
  357. self.resolve_js(file, compiler_resolved.add());
  358. });
  359. always_resolve(compiler_resolved.add());
  360. };
  361. /**
  362. * Read all .js files needed by compiler and eval() them.
  363. * The finished Compiler gets stored in defaults.smalltalk.
  364. * Followed by compile().
  365. */
  366. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  367. var self = this;
  368. var compiler_files = new Combo(function() {
  369. var builder = createConcatenator();
  370. builder.add('(function() {');
  371. builder.start();
  372. Array.prototype.slice.call(arguments).forEach(function(data) {
  373. // data is an array where index 0 is the error code and index 1 contains the data
  374. builder.add(data[1]);
  375. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  376. var match = ('' + data[1]).match(/^define\("([^"]*)"/);
  377. if (match) {
  378. builder.addId(match[1]);
  379. }
  380. });
  381. // store the generated smalltalk env in self.defaults.smalltalk
  382. builder.finish('self.defaults.smalltalk = smalltalk;');
  383. builder.add('})();');
  384. eval(builder.toString());
  385. console.log('Compiler loaded');
  386. self.defaults.smalltalk.ErrorHandler._setCurrent_(self.defaults.smalltalk.RethrowErrorHandler._new());
  387. if(0 != self.defaults.jsGlobals.length) {
  388. var jsGlobalVariables = self.defaults.smalltalk.globalJsVariables;
  389. jsGlobalVariables.push.apply(jsGlobalVariables, self.defaults.jsGlobals);
  390. }
  391. self.compile();
  392. });
  393. compilerFilesArray.forEach(function(file) {
  394. console.log('Loading file: ' + file);
  395. fs.readFile(file, compiler_files.add());
  396. });
  397. };
  398. /**
  399. * Compile all given .st files by importing them.
  400. * Followed by category_export().
  401. */
  402. AmberC.prototype.compile = function() {
  403. console.log('Compiling collected .st files')
  404. // import .st files
  405. var self = this;
  406. var imports = new Combo(function() {
  407. Array.prototype.slice.call(arguments).forEach(function(code) {
  408. if (undefined !== code[0]) {
  409. // get element 0 of code since all return values are stored inside an array by Combo
  410. self.defaults.smalltalk.Importer._new()._import_(code[0]._stream());
  411. }
  412. });
  413. self.category_export();
  414. });
  415. this.defaults.compile.forEach(function(stFile) {
  416. var callback = imports.add();
  417. if (/\.st/.test(stFile)) {
  418. console.ambercLog('Importing: ' + stFile);
  419. fs.readFile(stFile, 'utf8', function(err, data) {
  420. if (!err)
  421. callback(data);
  422. else
  423. throw new Error('Could not import: ' + stFile);
  424. });
  425. }
  426. });
  427. always_resolve(imports.add());
  428. };
  429. /**
  430. * Export compiled categories to JavaScript files.
  431. * Followed by verify().
  432. */
  433. AmberC.prototype.category_export = function() {
  434. var defaults = this.defaults;
  435. var self = this;
  436. // export categories as .js
  437. async_map(defaults.compile, function(stFile, callback) {
  438. var category = path.basename(stFile, '.st');
  439. var jsFilePath = defaults.output_dir;
  440. if (undefined === jsFilePath) {
  441. jsFilePath = path.dirname(stFile);
  442. }
  443. var jsFile = category + defaults.suffix_used + '.js';
  444. jsFile = path.join(jsFilePath, jsFile);
  445. defaults.compiled.push(jsFile);
  446. var smalltalk = defaults.smalltalk;
  447. var pluggableExporter = smalltalk.PluggableExporter;
  448. var packageObject = smalltalk.Package._named_(category);
  449. packageObject._transport()._namespace_(defaults.amd_namespace);
  450. fs.writeFile(jsFile, smalltalk.String._streamContents_(function (stream) {
  451. smalltalk.AmdExporter._new()._exportPackage_on_(packageObject, stream); }), function(err) {
  452. callback(null, null);
  453. });
  454. }, function(err, result){
  455. self.verify();
  456. });
  457. };
  458. /**
  459. * Verify if all .st files have been compiled.
  460. * Followed by compose_js_files().
  461. */
  462. AmberC.prototype.verify = function() {
  463. console.log('Verifying if all .st files were compiled');
  464. var self = this;
  465. // copy array
  466. var compiledFiles = this.defaults.compiled.slice(0);
  467. async_map(compiledFiles,
  468. function(file, callback) {
  469. fs.exists(file, function(exists) {
  470. if (exists)
  471. callback(null, null);
  472. else
  473. throw(new Error('Compilation failed of: ' + file));
  474. });
  475. }, function(err, result) {
  476. self.compose_js_files();
  477. });
  478. };
  479. /**
  480. * Synchronous function.
  481. * Concatenates compiled JavaScript files into one file in the correct order.
  482. * The name of the produced file is given by defaults.program (set by the last commandline option).
  483. */
  484. AmberC.prototype.compose_js_files = function() {
  485. var defaults = this.defaults;
  486. var self = this;
  487. var programFile = defaults.program;
  488. if (undefined === programFile) {
  489. return;
  490. }
  491. if (undefined !== defaults.output_dir) {
  492. programFile = path.join(defaults.output_dir, programFile);
  493. }
  494. var program_files = [];
  495. if (0 !== defaults.libraries.length) {
  496. console.log('Collecting libraries: ' + defaults.libraries);
  497. program_files.push.apply(program_files, defaults.libraries);
  498. }
  499. if (0 !== defaults.compiled.length) {
  500. var compiledFiles = defaults.compiled.slice(0);
  501. console.log('Collecting compiled files: ' + compiledFiles);
  502. program_files.push.apply(program_files, compiledFiles);
  503. }
  504. console.ambercLog('Writing program file: %s.js', programFile);
  505. var fileStream = fs.createWriteStream(programFile + defaults.suffix_used + '.js');
  506. fileStream.on('error', function(error) {
  507. fileStream.end();
  508. console.ambercLog(error);
  509. });
  510. fileStream.on('close', function(){
  511. return;
  512. });
  513. var builder = createConcatenator();
  514. builder.add('#!/usr/bin/env node');
  515. builder.start();
  516. program_files.forEach(function(file) {
  517. if(fs.existsSync(file)) {
  518. console.log('Adding : ' + file);
  519. var buffer = fs.readFileSync(file);
  520. // matches and returns the "module_id" string in the AMD define: define("module_id", ...)
  521. var match = buffer.toString().match(/^define\("([^"]*)"/);
  522. if (match /*&& match[1].slice(0,9) !== "amber_vm/"*/) {
  523. builder.addId(match[1]);
  524. }
  525. builder.add(buffer);
  526. } else {
  527. fileStream.end();
  528. throw(new Error('Can not find file ' + file));
  529. }
  530. });
  531. var mainFunctionOrFile = '';
  532. if (undefined !== defaults.main) {
  533. console.log('Adding call to: %s>>main', defaults.main);
  534. mainFunctionOrFile += 'smalltalk.' + defaults.main + '._main();';
  535. }
  536. if (undefined !== defaults.mainfile && fs.existsSync(defaults.mainfile)) {
  537. console.log('Adding main file: ' + defaults.mainfile);
  538. mainFunctionOrFile += '\n' + fs.readFileSync(defaults.mainfile);
  539. }
  540. builder.finish(mainFunctionOrFile);
  541. console.log('Writing...');
  542. builder.forEach(function (element) {
  543. fileStream.write(element);
  544. fileStream.write('\n');
  545. });
  546. console.log('Done.');
  547. fileStream.end();
  548. };
  549. module.exports.Compiler = AmberC;
  550. module.exports.createDefaults = createDefaults;
  551. module.exports.Combo = Combo;
  552. module.exports.map = async_map;