2
0

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