1
0

amberc.js 16 KB

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