1
0

amberc.js 16 KB

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