1
0

amberc.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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/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-Announcements',
  72. 'Platform-Services', 'Platform-Node'];
  73. this.compiler_libraries = this.kernel_libraries.concat(['parser', 'Platform-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. 'stFiles': [],
  83. 'jsGlobals': [],
  84. 'amd_namespace': 'amber_core',
  85. 'libraries': [],
  86. 'jsLibraryDirs': [],
  87. 'compile': [],
  88. 'compiled': [],
  89. 'output_dir': undefined,
  90. 'verbose': false
  91. };
  92. };
  93. /**
  94. * Main function for executing the compiler.
  95. * If check_configuration_ok() returns successfully
  96. * the configuration is used to trigger the following compilation steps.
  97. */
  98. AmberCompiler.prototype.main = function(configuration, finished_callback) {
  99. console.time('Compile Time');
  100. if (configuration.amd_namespace.length === 0) {
  101. configuration.amd_namespace = 'amber_core';
  102. }
  103. if (undefined !== configuration.jsLibraryDirs) {
  104. configuration.jsLibraryDirs.push(path.join(this.amber_dir, 'src'));
  105. configuration.jsLibraryDirs.push(path.join(this.amber_dir, 'support'));
  106. }
  107. console.ambercLog = console.log;
  108. if (false === configuration.verbose) {
  109. console.log = function() {};
  110. }
  111. // the evaluated compiler will be stored in this variable (see create_compiler)
  112. configuration.core = {};
  113. configuration.globals = {};
  114. configuration.kernel_libraries = this.kernel_libraries;
  115. configuration.compiler_libraries = this.compiler_libraries;
  116. configuration.amber_dir = this.amber_dir;
  117. check_configuration(configuration)
  118. .then(collect_st_files)
  119. .then(resolve_kernel)
  120. .then(create_compiler)
  121. .then(compile)
  122. .then(category_export)
  123. .then(verify)
  124. .then(function () {
  125. console.timeEnd('Compile Time');
  126. }, function(error) {
  127. console.error(error);
  128. })
  129. .then(function () {
  130. console.log = console.ambercLog;
  131. finished_callback && finished_callback();
  132. });
  133. };
  134. /**
  135. * Check if the passed in configuration object has sufficient/nonconflicting values.
  136. * Returns a Promise which resolves into the configuration object.
  137. */
  138. function check_configuration(configuration) {
  139. return new Promise(function(resolve, reject) {
  140. if (undefined === configuration) {
  141. reject(Error('AmberCompiler.check_configuration_ok(): missing configuration object'));
  142. }
  143. if (0 === configuration.stFiles.length) {
  144. reject(Error('AmberCompiler.check_configuration_ok(): no files to compile specified in configuration object'));
  145. }
  146. resolve(configuration);
  147. });
  148. };
  149. /**
  150. * Check if the file given as parameter exists in any of the following directories:
  151. * 1. current local directory
  152. * 2. configuration.jsLibraryDirs
  153. * 3. $AMBER/src/
  154. * 3. $AMBER/support/
  155. *
  156. * @param filename name of a file without '.js' prefix
  157. * @param configuration the main amberc configuration object
  158. */
  159. function resolve_js(filename, configuration) {
  160. var baseName = path.basename(filename, '.js');
  161. var jsFile = baseName + '.js';
  162. return resolve_file(jsFile, configuration.jsLibraryDirs);
  163. };
  164. /**
  165. * Check if the file given as parameter exists in any of the following directories:
  166. * 1. current local directory
  167. * 2. $AMBER/
  168. *
  169. * @param filename name of a .st file
  170. * @param configuration the main amberc configuration object
  171. */
  172. function resolve_st(filename, configuration) {
  173. return resolve_file(filename, [configuration.amber_dir]);
  174. };
  175. /**
  176. * Resolve the location of a file given as parameter filename.
  177. * First check if the file exists at given location,
  178. * then check in each of the directories specified in parameter searchDirectories.
  179. */
  180. function resolve_file(filename, searchDirectories) {
  181. return new Promise(function(resolve, reject) {
  182. console.log('Resolving: ' + filename);
  183. fs.exists(filename, function(exists) {
  184. if (exists) {
  185. resolve(filename);
  186. } else {
  187. var alternativeFile = '';
  188. // check for filename in any of the given searchDirectories
  189. var found = searchDirectories.some(function(directory) {
  190. alternativeFile = path.join(directory, filename);
  191. return fs.existsSync(alternativeFile);
  192. });
  193. if (found) {
  194. resolve(alternativeFile);
  195. } else {
  196. reject(Error('File not found: ' + alternativeFile));
  197. }
  198. }
  199. });
  200. });
  201. };
  202. /**
  203. * Resolve st files given by stFiles and add them to configuration.compile.
  204. * Returns a Promise which resolves into the configuration object.
  205. */
  206. function collect_st_files(configuration) {
  207. return Promise.all(
  208. configuration.stFiles.map(function(stFile) {
  209. return resolve_st(stFile, configuration);
  210. })
  211. )
  212. .then(function(data) {
  213. configuration.compile = configuration.compile.concat(data);
  214. return configuration;
  215. });
  216. }
  217. /**
  218. * Resolve .js files needed by kernel.
  219. * Returns a Promise which resolves into the configuration object.
  220. */
  221. function resolve_kernel(configuration) {
  222. var kernel_files = configuration.kernel_libraries.concat(configuration.load);
  223. return Promise.all(
  224. kernel_files.map(function(file) {
  225. return resolve_js(file, configuration);
  226. })
  227. )
  228. .then(function(data) {
  229. // boot.js and Kernel files need to be used first
  230. // otherwise the global objects 'core' and 'globals' are undefined
  231. configuration.libraries = data.concat(configuration.libraries);
  232. return configuration;
  233. });
  234. }
  235. function withImportsExcluded(data) {
  236. var srcLines = data.split(/\r\n|\r|\n/), dstLines = [], doCopy = true;
  237. srcLines.forEach(function (line) {
  238. if (line.replace(/\s/g, '') === '//>>excludeStart("imports",pragmas.excludeImports);') {
  239. doCopy = false;
  240. } else if (line.replace(/\s/g, '') === '//>>excludeEnd("imports");') {
  241. doCopy = true;
  242. } else if (doCopy) {
  243. dstLines.push(line);
  244. }
  245. });
  246. return dstLines.join('\n');
  247. }
  248. /**
  249. * Resolve .js files needed by compiler, read and eval() them.
  250. * The finished Compiler gets stored in configuration.{core,globals}.
  251. * Returns a Promise object which resolves into the configuration object.
  252. */
  253. function create_compiler(configuration) {
  254. var compiler_files = configuration.compiler_libraries;
  255. var include_files = configuration.load;
  256. var builder;
  257. return Promise.all(
  258. compiler_files.map(function(file) {
  259. return resolve_js(file, configuration);
  260. })
  261. )
  262. .then(function(compilerFilesArray) {
  263. return Promise.all(
  264. compilerFilesArray.map(function(file) {
  265. return new Promise(function(resolve, reject) {
  266. console.log('Loading file: ' + file);
  267. fs.readFile(file, function(err, data) {
  268. if (err)
  269. reject(err);
  270. else
  271. resolve(data);
  272. });
  273. });
  274. })
  275. )
  276. })
  277. .then(function(files) {
  278. builder = createConcatenator();
  279. builder.add('(function() {');
  280. builder.start();
  281. files.forEach(function(data) {
  282. // data is an array where index 0 is the error code and index 1 contains the data
  283. builder.add(data);
  284. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  285. var match = ('' + data).match(/(^|\n)define\("([^"]*)"/);
  286. if (match) {
  287. builder.addId(match[2]);
  288. }
  289. });
  290. })
  291. .then(function () { return Promise.all(
  292. include_files.map(function(file) {
  293. return resolve_js(file, configuration);
  294. })
  295. ); })
  296. .then(function(includeFilesArray) {
  297. return Promise.all(
  298. includeFilesArray.map(function(file) {
  299. return new Promise(function(resolve, reject) {
  300. console.log('Loading library file: ' + file);
  301. fs.readFile(file, function(err, data) {
  302. if (err)
  303. reject(err);
  304. else
  305. resolve(data);
  306. });
  307. });
  308. })
  309. )
  310. })
  311. .then(function(files) {
  312. var loadIds = [];
  313. files.forEach(function(data) {
  314. data = data + '';
  315. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  316. var match = data.match(/^define\("([^"]*)"/);
  317. if (match) {
  318. loadIds.push(match[1]);
  319. data = withImportsExcluded(data);
  320. }
  321. builder.add(data);
  322. });
  323. // store the generated smalltalk env in configuration.{core,globals}
  324. builder.finish('configuration.core = boot.api; configuration.globals = boot.globals;');
  325. loadIds.forEach(function (id) {
  326. builder.add('requirejs("' + id + '");');
  327. });
  328. builder.add('})();');
  329. eval(builder.toString());
  330. console.log('Compiler loaded');
  331. configuration.globals.ErrorHandler._register_(configuration.globals.RethrowErrorHandler._new());
  332. if(0 !== configuration.jsGlobals.length) {
  333. var jsGlobalVariables = configuration.core.globalJsVariables;
  334. jsGlobalVariables.push.apply(jsGlobalVariables, configuration.jsGlobals);
  335. }
  336. return configuration;
  337. });
  338. }
  339. /**
  340. * Compile all given .st files by importing them.
  341. * Returns a Promise object that resolves into the configuration object.
  342. */
  343. function compile(configuration) {
  344. // return function which does the actual work
  345. // and use the compile function to reference the configuration object
  346. return Promise.all(
  347. configuration.compile.map(function(stFile) {
  348. return new Promise(function(resolve, reject) {
  349. if (/\.st/.test(stFile)) {
  350. console.ambercLog('Reading: ' + stFile);
  351. fs.readFile(stFile, 'utf8', function(err, data) {
  352. if (!err)
  353. resolve(data);
  354. else
  355. reject(Error('Could not read: ' + stFile));
  356. });
  357. }
  358. });
  359. })
  360. )
  361. .then(function(fileContents) {
  362. console.log('Compiling collected .st files');
  363. // import/compile content of .st files
  364. return Promise.all(
  365. fileContents.map(function(code) {
  366. return new Promise(function(resolve, reject) {
  367. var importer = configuration.globals.Importer._new();
  368. try {
  369. importer._import_(code._stream());
  370. resolve(true);
  371. } catch (ex) {
  372. reject(Error("Compiler error in section:\n" +
  373. importer._lastSection() + "\n\n" +
  374. "while processing chunk:\n" +
  375. importer._lastChunk() + "\n\n" +
  376. (ex._messageText && ex._messageText() || ex.message || ex))
  377. );
  378. }
  379. });
  380. })
  381. );
  382. })
  383. .then(function () {
  384. return configuration;
  385. });
  386. }
  387. /**
  388. * Export compiled categories to JavaScript files.
  389. * Returns a Promise() that resolves into the configuration object.
  390. */
  391. function category_export(configuration) {
  392. return Promise.all(
  393. configuration.compile.map(function(stFile) {
  394. return new Promise(function(resolve, reject) {
  395. var category = path.basename(stFile, '.st');
  396. var jsFilePath = configuration.output_dir;
  397. if (undefined === jsFilePath) {
  398. jsFilePath = path.dirname(stFile);
  399. }
  400. var jsFile = category + '.js';
  401. jsFile = path.join(jsFilePath, jsFile);
  402. configuration.compiled.push(jsFile);
  403. var smalltalkGlobals = configuration.globals;
  404. var packageObject = smalltalkGlobals.Package._named_(category);
  405. packageObject._transport()._namespace_(configuration.amd_namespace);
  406. fs.writeFile(jsFile, smalltalkGlobals.String._streamContents_(function (stream) {
  407. smalltalkGlobals.AmdExporter._new()._exportPackage_on_(packageObject, stream);
  408. }), function(err) {
  409. if (err)
  410. reject(err);
  411. else
  412. resolve(true);
  413. });
  414. });
  415. })
  416. )
  417. .then(function() {
  418. return configuration;
  419. });
  420. }
  421. /**
  422. * Verify if all .st files have been compiled.
  423. * Returns a Promise() that resolves into the configuration object.
  424. */
  425. function verify(configuration) {
  426. console.log('Verifying if all .st files were compiled');
  427. return Promise.all(
  428. configuration.compiled.map(function(file) {
  429. return new Promise(function(resolve, reject) {
  430. fs.exists(file, function(exists) {
  431. if (exists)
  432. resolve(true);
  433. else
  434. reject(Error('Compilation failed of: ' + file));
  435. });
  436. });
  437. })
  438. )
  439. .then(function() {
  440. return configuration;
  441. });
  442. }
  443. module.exports.Compiler = AmberCompiler;
  444. module.exports.createDefaultConfiguration = createDefaultConfiguration;