amberc.js 17 KB

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