amberc.js 12 KB

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