amberc.js 17 KB

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