amberc.js 17 KB

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