amberc.js 14 KB

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