2
0

amberc.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. var include_files = configuration.load;
  266. var builder;
  267. return Promise.all(
  268. compiler_files.map(function(file) {
  269. return resolve_js(file, configuration);
  270. })
  271. )
  272. .then(function(compilerFilesArray) {
  273. return Promise.all(
  274. compilerFilesArray.map(function(file) {
  275. return new Promise(function(resolve, reject) {
  276. console.log('Loading file: ' + file);
  277. fs.readFile(file, function(err, data) {
  278. if (err)
  279. reject(err);
  280. else
  281. resolve(data);
  282. });
  283. });
  284. })
  285. )
  286. })
  287. .then(function(files) {
  288. builder = createConcatenator();
  289. builder.add('(function() {');
  290. builder.start();
  291. files.forEach(function(data) {
  292. // data is an array where index 0 is the error code and index 1 contains the data
  293. builder.add(data);
  294. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  295. var match = ('' + data).match(/^define\("([^"]*)"/);
  296. if (match) {
  297. builder.addId(match[1]);
  298. }
  299. });
  300. })
  301. .then(function () { return Promise.all(
  302. include_files.map(function(file) {
  303. return resolve_js(file, configuration);
  304. })
  305. ); })
  306. .then(function(includeFilesArray) {
  307. return Promise.all(
  308. includeFilesArray.map(function(file) {
  309. return new Promise(function(resolve, reject) {
  310. console.log('Loading library file: ' + file);
  311. fs.readFile(file, function(err, data) {
  312. if (err)
  313. reject(err);
  314. else
  315. resolve(data);
  316. });
  317. });
  318. })
  319. )
  320. })
  321. .then(function(files) {
  322. var loadIds = [];
  323. files.forEach(function(data) {
  324. // data is an array where index 0 is the error code and index 1 contains the data
  325. builder.add(data);
  326. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  327. var match = ('' + data).match(/^define\("([^"]*)"/);
  328. if (match) {
  329. loadIds.push(match[1]);
  330. }
  331. });
  332. // store the generated smalltalk env in configuration.{vm,globals}
  333. builder.finish('configuration.vm = vm; configuration.globals = globals;');
  334. loadIds.forEach(function (id) {
  335. builder.add('requirejs("' + id + '");');
  336. });
  337. builder.add('})();');
  338. eval(builder.toString());
  339. console.log('Compiler loaded');
  340. configuration.globals.ErrorHandler._register_(configuration.globals.RethrowErrorHandler._new());
  341. if(0 !== configuration.jsGlobals.length) {
  342. var jsGlobalVariables = configuration.vm.globalJsVariables;
  343. jsGlobalVariables.push.apply(jsGlobalVariables, configuration.jsGlobals);
  344. }
  345. return configuration;
  346. });
  347. }
  348. /**
  349. * Compile all given .st files by importing them.
  350. * Returns a Promise object that resolves into the configuration object.
  351. */
  352. function compile(configuration) {
  353. // return function which does the actual work
  354. // and use the compile function to reference the configuration object
  355. return Promise.all(
  356. configuration.compile.map(function(stFile) {
  357. return new Promise(function(resolve, reject) {
  358. if (/\.st/.test(stFile)) {
  359. console.ambercLog('Reading: ' + stFile);
  360. fs.readFile(stFile, 'utf8', function(err, data) {
  361. if (!err)
  362. resolve(data);
  363. else
  364. reject(Error('Could not read: ' + stFile));
  365. });
  366. }
  367. });
  368. })
  369. )
  370. .then(function(fileContents) {
  371. console.log('Compiling collected .st files');
  372. // import/compile content of .st files
  373. return Promise.all(
  374. fileContents.map(function(code) {
  375. return new Promise(function(resolve, reject) {
  376. var importer = configuration.globals.Importer._new();
  377. try {
  378. importer._import_(code._stream());
  379. resolve(true);
  380. } catch (ex) {
  381. reject(Error("Compiler error in section:\n" +
  382. importer._lastSection() + "\n\n" +
  383. "while processing chunk:\n" +
  384. importer._lastChunk() + "\n\n" +
  385. (ex._messageText && ex._messageText() || ex.message || ex))
  386. );
  387. }
  388. });
  389. })
  390. );
  391. })
  392. .then(function () {
  393. return configuration;
  394. });
  395. }
  396. /**
  397. * Export compiled categories to JavaScript files.
  398. * Returns a Promise() that resolves into the configuration object.
  399. */
  400. function category_export(configuration) {
  401. return Promise.all(
  402. configuration.compile.map(function(stFile) {
  403. return new Promise(function(resolve, reject) {
  404. var category = path.basename(stFile, '.st');
  405. var jsFilePath = configuration.output_dir;
  406. if (undefined === jsFilePath) {
  407. jsFilePath = path.dirname(stFile);
  408. }
  409. var jsFile = category + configuration.suffix_used + '.js';
  410. jsFile = path.join(jsFilePath, jsFile);
  411. configuration.compiled.push(jsFile);
  412. var smalltalkGlobals = configuration.globals;
  413. var packageObject = smalltalkGlobals.Package._named_(category);
  414. packageObject._transport()._namespace_(configuration.amd_namespace);
  415. fs.writeFile(jsFile, smalltalkGlobals.String._streamContents_(function (stream) {
  416. smalltalkGlobals.AmdExporter._new()._exportPackage_on_(packageObject, stream);
  417. }), function(err) {
  418. if (err)
  419. reject(err);
  420. else
  421. resolve(true);
  422. });
  423. });
  424. })
  425. )
  426. .then(function() {
  427. return configuration;
  428. });
  429. }
  430. /**
  431. * Verify if all .st files have been compiled.
  432. * Returns a Promise() that resolves into the configuration object.
  433. */
  434. function verify(configuration) {
  435. console.log('Verifying if all .st files were compiled');
  436. return Promise.all(
  437. configuration.compiled.map(function(file) {
  438. return new Promise(function(resolve, reject) {
  439. fs.exists(file, function(exists) {
  440. if (exists)
  441. resolve(true);
  442. else
  443. reject(Error('Compilation failed of: ' + file));
  444. });
  445. });
  446. })
  447. )
  448. .then(function() {
  449. return configuration;
  450. });
  451. }
  452. /**
  453. * Synchronous function.
  454. * Concatenates compiled JavaScript files into one file in the correct order.
  455. * The name of the produced file is given by configuration.program.
  456. * Returns a Promise which resolves into the configuration object.
  457. */
  458. function compose_js_files(configuration) {
  459. return new Promise(function(resolve, reject) {
  460. var programFile = configuration.program;
  461. if (undefined === programFile) {
  462. resolve(configuration);
  463. return;
  464. }
  465. if (undefined !== configuration.output_dir) {
  466. programFile = path.join(configuration.output_dir, programFile);
  467. }
  468. var program_files = [];
  469. if (0 !== configuration.libraries.length) {
  470. console.log('Collecting libraries: ' + configuration.libraries);
  471. program_files.push.apply(program_files, configuration.libraries);
  472. }
  473. if (0 !== configuration.compiled.length) {
  474. var compiledFiles = configuration.compiled.slice(0);
  475. console.log('Collecting compiled files: ' + compiledFiles);
  476. program_files.push.apply(program_files, compiledFiles);
  477. }
  478. console.ambercLog('Writing program file: %s.js', programFile);
  479. var fileStream = fs.createWriteStream(programFile + configuration.suffix_used + '.js');
  480. fileStream.on('error', function(error) {
  481. fileStream.end();
  482. console.ambercLog(error);
  483. reject(error);
  484. });
  485. fileStream.on('close', function(){
  486. resolve(configuration);
  487. });
  488. var builder = createConcatenator();
  489. builder.add('#!/usr/bin/env node');
  490. builder.start();
  491. program_files.forEach(function(file) {
  492. if(fs.existsSync(file)) {
  493. console.log('Adding : ' + file);
  494. var buffer = fs.readFileSync(file);
  495. // matches and returns the "module_id" string in the AMD define: define("module_id", ...)
  496. var match = buffer.toString().match(/^define\("([^"]*)"/);
  497. if (match /*&& match[1].slice(0,9) !== "amber_vm/"*/) {
  498. builder.addId(match[1]);
  499. }
  500. builder.add(buffer);
  501. } else {
  502. fileStream.end();
  503. reject(Error('Can not find file ' + file));
  504. }
  505. });
  506. var mainFunctionOrFile = '';
  507. if (undefined !== configuration.main) {
  508. console.log('Adding call to: %s>>main', configuration.main);
  509. mainFunctionOrFile += 'globals.' + configuration.main + '._main();';
  510. }
  511. if (undefined !== configuration.mainfile && fs.existsSync(configuration.mainfile)) {
  512. console.log('Adding main file: ' + configuration.mainfile);
  513. mainFunctionOrFile += '\nvar smalltalk = vm; // backward compatibility\n' + fs.readFileSync(configuration.mainfile);
  514. }
  515. builder.finish(mainFunctionOrFile);
  516. console.log('Writing...');
  517. builder.forEach(function (element) {
  518. fileStream.write(element);
  519. fileStream.write('\n');
  520. });
  521. console.log('Done.');
  522. fileStream.end();
  523. });
  524. }
  525. module.exports.Compiler = AmberCompiler;
  526. module.exports.createDefaultConfiguration = createDefaultConfiguration;