amberc.js 14 KB

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