amberc.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. var path = require('path'),
  11. fs = require('fs'),
  12. Promise = require('es6-promise').Promise,
  13. requirejs = require('requirejs');
  14. /**
  15. * AmberCompiler constructor function.
  16. * amber_dir: points to the location of an amber installation
  17. */
  18. function AmberCompiler(amber_dir) {
  19. if (amber_dir == null || !fs.existsSync(amber_dir)) {
  20. throw new Error('amber_dir needs to be a valid directory');
  21. }
  22. this.amber_dir = amber_dir;
  23. }
  24. /**
  25. * Default values.
  26. */
  27. var createDefaultConfiguration = function () {
  28. return {
  29. paths: {},
  30. configFile: null,
  31. load: [],
  32. stFiles: [],
  33. jsGlobals: [],
  34. amdNamespace: 'amber_core',
  35. compile: [],
  36. compiled: [],
  37. outputDir: undefined,
  38. verbose: false
  39. };
  40. };
  41. /**
  42. * Main function for executing the compiler.
  43. * If check_configuration_ok() returns successfully
  44. * the configuration is used to trigger the following compilation steps.
  45. */
  46. AmberCompiler.prototype.main = function (configuration, finished_callback) {
  47. console.time('Compile Time');
  48. if (configuration.amdNamespace.length === 0) {
  49. configuration.amdNamespace = 'amber_core';
  50. }
  51. console.ambercLog = console.log;
  52. if (false === configuration.verbose) {
  53. console.log = function () {
  54. };
  55. }
  56. // the evaluated compiler will be stored in this variable (see create_compiler)
  57. configuration.core = {};
  58. configuration.globals = {};
  59. configuration.amber_dir = this.amber_dir;
  60. var rjsConfig;
  61. if (configuration.configFile) {
  62. var configSrc = fs.readFileSync(configuration.configFile, "utf8");
  63. rjsConfig = (function () {
  64. var require, requirejs;
  65. requirejs = require = {
  66. config: function (x) {
  67. requirejs = require = x;
  68. }
  69. };
  70. eval(configSrc);
  71. return require;
  72. })();
  73. } else {
  74. rjsConfig = {
  75. paths: configuration.paths
  76. };
  77. }
  78. if (!rjsConfig.paths.amber) rjsConfig.paths.amber = path.join(this.amber_dir, 'support');
  79. if (!rjsConfig.paths.amber_core) rjsConfig.paths.amber_core = path.join(this.amber_dir, 'src');
  80. rjsConfig.paths['text'] = require.resolve('requirejs-text').replace(/\.js$/, "");
  81. rjsConfig.paths['amber/without-imports'] = path.join(__dirname, 'without-imports');
  82. rjsConfig.nodeRequire = require;
  83. rjsConfig.context = "amberc";
  84. configuration.requirejs = requirejs.config(rjsConfig);
  85. check_configuration(configuration)
  86. .then(collect_st_files)
  87. .then(create_compiler)
  88. .then(compile)
  89. .then(category_export)
  90. .then(verify)
  91. .then(function () {
  92. console.timeEnd('Compile Time');
  93. }, function (error) {
  94. console.error(error);
  95. })
  96. .then(function () {
  97. console.log = console.ambercLog;
  98. finished_callback && finished_callback();
  99. });
  100. };
  101. /**
  102. * Check if the passed in configuration object has sufficient/nonconflicting values.
  103. * Returns a Promise which resolves into the configuration object.
  104. */
  105. function check_configuration(configuration) {
  106. return new Promise(function (resolve, reject) {
  107. if (configuration == null) {
  108. reject(Error('AmberCompiler.check_configuration_ok(): missing configuration object'));
  109. }
  110. if (0 === configuration.stFiles.length) {
  111. reject(Error('AmberCompiler.check_configuration_ok(): no files to compile specified in configuration object'));
  112. }
  113. resolve(configuration);
  114. });
  115. }
  116. /**
  117. * Check if the file given as parameter exists in any of the following directories:
  118. * 1. current local directory
  119. * 2. $AMBER/
  120. *
  121. * @param filename name of a .st file
  122. * @param configuration the main amberc configuration object
  123. */
  124. function resolve_st(filename, configuration) {
  125. return resolve_file(filename, [configuration.amber_dir]);
  126. }
  127. /**
  128. * Resolve the location of a file given as parameter filename.
  129. * First check if the file exists at given location,
  130. * then check in each of the directories specified in parameter searchDirectories.
  131. */
  132. function resolve_file(filename, searchDirectories) {
  133. return new Promise(function (resolve, reject) {
  134. console.log('Resolving: ' + filename);
  135. fs.exists(filename, function (exists) {
  136. if (exists) {
  137. resolve(filename);
  138. } else {
  139. var alternativeFile = '';
  140. // check for filename in any of the given searchDirectories
  141. var found = searchDirectories.some(function (directory) {
  142. alternativeFile = path.join(directory, filename);
  143. return fs.existsSync(alternativeFile);
  144. });
  145. if (found) {
  146. resolve(alternativeFile);
  147. } else {
  148. reject(Error('File not found: ' + alternativeFile));
  149. }
  150. }
  151. });
  152. });
  153. }
  154. /**
  155. * Resolve st files given by stFiles and add them to configuration.compile.
  156. * Returns a Promise which resolves into the configuration object.
  157. */
  158. function collect_st_files(configuration) {
  159. return Promise.all(
  160. configuration.stFiles.map(function (stFile) {
  161. return resolve_st(stFile, configuration);
  162. })
  163. )
  164. .then(function (data) {
  165. configuration.compile = configuration.compile.concat(data);
  166. return configuration;
  167. });
  168. }
  169. /**
  170. * Resolve .js files needed by compiler, read and eval() them.
  171. * The finished Compiler gets stored in configuration.{core,globals}.
  172. * Returns a Promise object which resolves into the configuration object.
  173. */
  174. function create_compiler(configuration) {
  175. var include_files = configuration.load;
  176. return new Promise(configuration.requirejs.bind(null, ["amber/lang", "amber_core/Platform-Node"]))
  177. .then(function (boot) {
  178. configuration.core = boot.api;
  179. configuration.globals = boot.globals;
  180. return boot.api.initialize();
  181. })
  182. .then(function () {
  183. var pluginPrefixedLibraries = include_files.map(function (each) {
  184. return 'amber/without-imports!' + each;
  185. });
  186. return new Promise(configuration.requirejs.bind(null, pluginPrefixedLibraries));
  187. })
  188. .then(function () {
  189. configuration.globals.AmberBootstrapInitialization._organizeClasses();
  190. (configuration.globals.Smalltalk._adoptPackageDictionary || configuration.globals.Smalltalk._adoptPackageDescriptors).call(configuration.globals.Smalltalk);
  191. console.log('Compiler loaded');
  192. configuration.jsGlobals.forEach(function (each) {
  193. configuration.globals.Smalltalk._addGlobalJsVariable_(each);
  194. });
  195. return configuration;
  196. });
  197. }
  198. /**
  199. * Compile all given .st files by importing them.
  200. * Returns a Promise object that resolves into the configuration object.
  201. */
  202. function compile(configuration) {
  203. // return function which does the actual work
  204. // and use the compile function to reference the configuration object
  205. return Promise.all(
  206. configuration.compile.map(function (stFile) {
  207. return new Promise(function (resolve, reject) {
  208. if (/\.st/.test(stFile)) {
  209. console.ambercLog('Reading: ' + stFile);
  210. fs.readFile(stFile, 'utf8', function (err, data) {
  211. if (!err)
  212. resolve(data);
  213. else
  214. reject(Error('Could not read: ' + stFile));
  215. });
  216. }
  217. });
  218. })
  219. )
  220. .then(function (fileContents) {
  221. console.log('Compiling collected .st files');
  222. // import/compile content of .st files
  223. return Promise.all(
  224. fileContents.map(function (code) {
  225. return new Promise(function (resolve, reject) {
  226. var importer = configuration.globals.Importer._new();
  227. try {
  228. importer._import_(code._stream());
  229. resolve(true);
  230. } catch (ex) {
  231. reject(Error("Compiler error in section:\n" +
  232. importer._lastSection() + "\n\n" +
  233. "while processing chunk:\n" +
  234. importer._lastChunk() + "\n\n" +
  235. (ex._messageText && ex._messageText() || ex.message || ex))
  236. );
  237. }
  238. });
  239. })
  240. );
  241. })
  242. .then(function () {
  243. return configuration;
  244. });
  245. }
  246. /**
  247. * Export compiled categories to JavaScript files.
  248. * Returns a Promise() that resolves into the configuration object.
  249. */
  250. function category_export(configuration) {
  251. return Promise.all(
  252. configuration.compile.map(function (stFile) {
  253. return new Promise(function (resolve, reject) {
  254. var category = path.basename(stFile, '.st');
  255. var jsFilePath = configuration.outputDir;
  256. if (jsFilePath == null) {
  257. jsFilePath = path.dirname(stFile);
  258. }
  259. var jsFile = category + '.js';
  260. jsFile = path.join(jsFilePath, jsFile);
  261. configuration.compiled.push(jsFile);
  262. var smalltalkGlobals = configuration.globals;
  263. var packageObject = smalltalkGlobals.Package._named_(category);
  264. packageObject._transport()._namespace_(configuration.amdNamespace);
  265. fs.writeFile(jsFile, smalltalkGlobals.String._streamContents_(function (stream) {
  266. smalltalkGlobals.AmdExporter._new()._exportPackage_on_(packageObject, stream);
  267. }), function (err) {
  268. if (err)
  269. reject(err);
  270. else
  271. resolve(true);
  272. });
  273. });
  274. })
  275. )
  276. .then(function () {
  277. return configuration;
  278. });
  279. }
  280. /**
  281. * Verify if all .st files have been compiled.
  282. * Returns a Promise() that resolves into the configuration object.
  283. */
  284. function verify(configuration) {
  285. console.log('Verifying if all .st files were compiled');
  286. return Promise.all(
  287. configuration.compiled.map(function (file) {
  288. return new Promise(function (resolve, reject) {
  289. fs.exists(file, function (exists) {
  290. if (exists)
  291. resolve(true);
  292. else
  293. reject(Error('Compilation failed of: ' + file));
  294. });
  295. });
  296. })
  297. )
  298. .then(function () {
  299. return configuration;
  300. });
  301. }
  302. module.exports.Compiler = AmberCompiler;
  303. module.exports.createDefaultConfiguration = createDefaultConfiguration;