amberc.js 12 KB

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