amberc.js 11 KB

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