1
0

amberc.js 15 KB

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