amberc.js 16 KB

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