amberc.js 17 KB

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