amberc.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. 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. }
  30. });
  31. // Important: in next list, boot MUST be first
  32. this.kernel_libraries = ['amber/boot',
  33. 'amber_core/Kernel-Objects', 'amber_core/Kernel-Classes', 'amber_core/Kernel-Methods',
  34. 'amber_core/Kernel-Collections', 'amber_core/Kernel-Infrastructure',
  35. 'amber_core/Kernel-Exceptions', 'amber_core/Kernel-Announcements',
  36. 'amber_core/Platform-Services', 'amber_core/Platform-Node'];
  37. this.compiler_libraries = this.kernel_libraries.concat(['amber/parser',
  38. 'amber_core/Platform-ImportExport', 'amber_core/Compiler-Exceptions',
  39. 'amber_core/Compiler-Core', 'amber_core/Compiler-AST', 'amber_core/Compiler-Exceptions',
  40. 'amber_core/Compiler-IR', 'amber_core/Compiler-Inlining', 'amber_core/Compiler-Semantic']);
  41. }
  42. /**
  43. * Default values.
  44. */
  45. var createDefaultConfiguration = function () {
  46. return {
  47. load: [],
  48. stFiles: [],
  49. jsGlobals: [],
  50. amdNamespace: 'amber_core',
  51. libraries: [],
  52. jsLibraryDirs: [],
  53. compile: [],
  54. compiled: [],
  55. outputDir: undefined,
  56. verbose: false
  57. };
  58. };
  59. /**
  60. * Main function for executing the compiler.
  61. * If check_configuration_ok() returns successfully
  62. * the configuration is used to trigger the following compilation steps.
  63. */
  64. AmberCompiler.prototype.main = function (configuration, finished_callback) {
  65. console.time('Compile Time');
  66. if (configuration.amdNamespace.length === 0) {
  67. configuration.amdNamespace = 'amber_core';
  68. }
  69. if (configuration.jsLibraryDirs != null) {
  70. configuration.jsLibraryDirs.push(path.join(this.amber_dir, 'src'));
  71. configuration.jsLibraryDirs.push(path.join(this.amber_dir, 'support'));
  72. }
  73. console.ambercLog = console.log;
  74. if (false === configuration.verbose) {
  75. console.log = function () {
  76. };
  77. }
  78. // the evaluated compiler will be stored in this variable (see create_compiler)
  79. configuration.core = {};
  80. configuration.globals = {};
  81. configuration.kernel_libraries = this.kernel_libraries;
  82. configuration.compiler_libraries = this.compiler_libraries;
  83. configuration.amber_dir = this.amber_dir;
  84. check_configuration(configuration)
  85. .then(collect_st_files)
  86. .then(resolve_kernel)
  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. configuration.jsLibraryDirs
  120. * 3. $AMBER/src/
  121. * 3. $AMBER/support/
  122. *
  123. * @param filename name of a file without '.js' prefix
  124. * @param configuration the main amberc configuration object
  125. */
  126. function resolve_js(filename, configuration) {
  127. var baseName = path.basename(filename, '.js');
  128. var jsFile = baseName + '.js';
  129. return resolve_file(jsFile, configuration.jsLibraryDirs);
  130. }
  131. /**
  132. * Check if the file given as parameter exists in any of the following directories:
  133. * 1. current local directory
  134. * 2. $AMBER/
  135. *
  136. * @param filename name of a .st file
  137. * @param configuration the main amberc configuration object
  138. */
  139. function resolve_st(filename, configuration) {
  140. return resolve_file(filename, [configuration.amber_dir]);
  141. }
  142. /**
  143. * Resolve the location of a file given as parameter filename.
  144. * First check if the file exists at given location,
  145. * then check in each of the directories specified in parameter searchDirectories.
  146. */
  147. function resolve_file(filename, searchDirectories) {
  148. return new Promise(function (resolve, reject) {
  149. console.log('Resolving: ' + filename);
  150. fs.exists(filename, function (exists) {
  151. if (exists) {
  152. resolve(filename);
  153. } else {
  154. var alternativeFile = '';
  155. // check for filename in any of the given searchDirectories
  156. var found = searchDirectories.some(function (directory) {
  157. alternativeFile = path.join(directory, filename);
  158. return fs.existsSync(alternativeFile);
  159. });
  160. if (found) {
  161. resolve(alternativeFile);
  162. } else {
  163. reject(Error('File not found: ' + alternativeFile));
  164. }
  165. }
  166. });
  167. });
  168. }
  169. /**
  170. * Resolve st files given by stFiles and add them to configuration.compile.
  171. * Returns a Promise which resolves into the configuration object.
  172. */
  173. function collect_st_files(configuration) {
  174. return Promise.all(
  175. configuration.stFiles.map(function (stFile) {
  176. return resolve_st(stFile, configuration);
  177. })
  178. )
  179. .then(function (data) {
  180. configuration.compile = configuration.compile.concat(data);
  181. return configuration;
  182. });
  183. }
  184. /**
  185. * Resolve .js files needed by kernel.
  186. * Returns a Promise which resolves into the configuration object.
  187. */
  188. function resolve_kernel(configuration) {
  189. var kernel_files = configuration.kernel_libraries.concat(configuration.load);
  190. return Promise.all(
  191. kernel_files.map(function (file) {
  192. return resolve_js(file, configuration);
  193. })
  194. )
  195. .then(function (data) {
  196. // boot.js and Kernel files need to be used first
  197. // otherwise the global objects 'core' and 'globals' are undefined
  198. configuration.libraries = data.concat(configuration.libraries);
  199. return configuration;
  200. });
  201. }
  202. function withImportsExcluded(data) {
  203. var srcLines = data.split(/\r\n|\r|\n/), dstLines = [], doCopy = true;
  204. srcLines.forEach(function (line) {
  205. if (line.replace(/\s/g, '') === '//>>excludeStart("imports",pragmas.excludeImports);') {
  206. doCopy = false;
  207. } else if (line.replace(/\s/g, '') === '//>>excludeEnd("imports");') {
  208. doCopy = true;
  209. } else if (doCopy) {
  210. dstLines.push(line);
  211. }
  212. });
  213. return dstLines.join('\n');
  214. }
  215. /**
  216. * Resolve .js files needed by compiler, read and eval() them.
  217. * The finished Compiler gets stored in configuration.{core,globals}.
  218. * Returns a Promise object which resolves into the configuration object.
  219. */
  220. function create_compiler(configuration) {
  221. var compiler_files = configuration.compiler_libraries;
  222. var include_files = configuration.load;
  223. return new Promise(function (resolve, reject) {
  224. requirejs(compiler_files, function (boot) {
  225. configuration.core = boot.api;
  226. configuration.globals = boot.globals;
  227. resolve(configuration);
  228. }, function (err) {
  229. reject(err);
  230. });
  231. })
  232. .then(function (configuration) {
  233. var files = []; // TODO load -L libraries while filtering their imports
  234. files.forEach(function (data) {
  235. data = data + '';
  236. data = withImportsExcluded(data);
  237. //builder.add(data);
  238. });
  239. configuration.core.initialize();
  240. console.log('Compiler loaded');
  241. configuration.globals.ErrorHandler._register_(configuration.globals.RethrowErrorHandler._new());
  242. if (0 !== configuration.jsGlobals.length) {
  243. var jsGlobalVariables = configuration.core.globalJsVariables;
  244. jsGlobalVariables.push.apply(jsGlobalVariables, configuration.jsGlobals);
  245. }
  246. return configuration;
  247. });
  248. }
  249. /**
  250. * Compile all given .st files by importing them.
  251. * Returns a Promise object that resolves into the configuration object.
  252. */
  253. function compile(configuration) {
  254. // return function which does the actual work
  255. // and use the compile function to reference the configuration object
  256. return Promise.all(
  257. configuration.compile.map(function (stFile) {
  258. return new Promise(function (resolve, reject) {
  259. if (/\.st/.test(stFile)) {
  260. console.ambercLog('Reading: ' + stFile);
  261. fs.readFile(stFile, 'utf8', function (err, data) {
  262. if (!err)
  263. resolve(data);
  264. else
  265. reject(Error('Could not read: ' + stFile));
  266. });
  267. }
  268. });
  269. })
  270. )
  271. .then(function (fileContents) {
  272. console.log('Compiling collected .st files');
  273. // import/compile content of .st files
  274. return Promise.all(
  275. fileContents.map(function (code) {
  276. return new Promise(function (resolve, reject) {
  277. var importer = configuration.globals.Importer._new();
  278. try {
  279. importer._import_(code._stream());
  280. resolve(true);
  281. } catch (ex) {
  282. reject(Error("Compiler error in section:\n" +
  283. importer._lastSection() + "\n\n" +
  284. "while processing chunk:\n" +
  285. importer._lastChunk() + "\n\n" +
  286. (ex._messageText && ex._messageText() || ex.message || ex))
  287. );
  288. }
  289. });
  290. })
  291. );
  292. })
  293. .then(function () {
  294. return configuration;
  295. });
  296. }
  297. /**
  298. * Export compiled categories to JavaScript files.
  299. * Returns a Promise() that resolves into the configuration object.
  300. */
  301. function category_export(configuration) {
  302. return Promise.all(
  303. configuration.compile.map(function (stFile) {
  304. return new Promise(function (resolve, reject) {
  305. var category = path.basename(stFile, '.st');
  306. var jsFilePath = configuration.outputDir;
  307. if (jsFilePath == null) {
  308. jsFilePath = path.dirname(stFile);
  309. }
  310. var jsFile = category + '.js';
  311. jsFile = path.join(jsFilePath, jsFile);
  312. configuration.compiled.push(jsFile);
  313. var smalltalkGlobals = configuration.globals;
  314. var packageObject = smalltalkGlobals.Package._named_(category);
  315. packageObject._transport()._namespace_(configuration.amdNamespace);
  316. fs.writeFile(jsFile, smalltalkGlobals.String._streamContents_(function (stream) {
  317. smalltalkGlobals.AmdExporter._new()._exportPackage_on_(packageObject, stream);
  318. }), function (err) {
  319. if (err)
  320. reject(err);
  321. else
  322. resolve(true);
  323. });
  324. });
  325. })
  326. )
  327. .then(function () {
  328. return configuration;
  329. });
  330. }
  331. /**
  332. * Verify if all .st files have been compiled.
  333. * Returns a Promise() that resolves into the configuration object.
  334. */
  335. function verify(configuration) {
  336. console.log('Verifying if all .st files were compiled');
  337. return Promise.all(
  338. configuration.compiled.map(function (file) {
  339. return new Promise(function (resolve, reject) {
  340. fs.exists(file, function (exists) {
  341. if (exists)
  342. resolve(true);
  343. else
  344. reject(Error('Compilation failed of: ' + file));
  345. });
  346. });
  347. })
  348. )
  349. .then(function () {
  350. return configuration;
  351. });
  352. }
  353. module.exports.Compiler = AmberCompiler;
  354. module.exports.createDefaultConfiguration = createDefaultConfiguration;