kernel-runtime.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. //jshint eqnull:true
  2. define(['./junk-drawer'], function ($goodies) {
  3. "use strict";
  4. var installMethodOfJsObject = $goodies.installMethodOfJsObject;
  5. var declareJsMethod = $goodies.declareJsMethod;
  6. var st2js = $goodies.st2js;
  7. var js2st = $goodies.js2st;
  8. var deleteKeysFrom = $goodies.deleteKeysFrom;
  9. var extendWithMethods = $goodies.extendWithMethods;
  10. function uninstallMethodOfJsObjectEx (obj, name) {
  11. var attachments;
  12. var old = Object.getOwnPropertyDescriptor(obj, name);
  13. if (old != null && (old = old.value) != null) {
  14. attachments = old.a$atx;
  15. if (attachments != null) {
  16. deleteKeysFrom(Object.keys(attachments), obj);
  17. }
  18. }
  19. delete obj[name];
  20. }
  21. function installMethodOfJsObjectEx (obj, name, fn) {
  22. uninstallMethodOfJsObjectEx(obj, name);
  23. var attachments = fn.a$atx;
  24. if (attachments != null) {
  25. extendWithMethods(obj, attachments);
  26. }
  27. return installMethodOfJsObject(obj, name, fn);
  28. }
  29. function SelectorConversionBrik (brikz, st) {
  30. var st2jsMemo = Object.create(null);
  31. st.st2js = function (stSelector) {
  32. return st2jsMemo[stSelector] || st2js(stSelector);
  33. };
  34. this.st2js = function (stSelector) {
  35. return st2jsMemo[stSelector] || (st2jsMemo[stSelector] = st2js(stSelector));
  36. };
  37. /* Convert a string to a valid smalltalk selector.
  38. if you modify the following functions, also change st2js
  39. accordingly */
  40. st.js2st = js2st;
  41. st.st2prop = function (stSelector) {
  42. var colonPosition = stSelector.indexOf(':');
  43. return colonPosition === -1 ? stSelector : stSelector.slice(0, colonPosition);
  44. };
  45. }
  46. function RuntimeFactory (globals, emit) {
  47. RuntimeSelectorsBrik.deps = ["selectors", "selectorConversion", "classModel"];
  48. function RuntimeSelectorsBrik (brikz, st) {
  49. var selectors = brikz.selectors.selectors;
  50. var nilAsClass = brikz.classModel.nilAsClass;
  51. var st2js = brikz.selectorConversion.st2js;
  52. var jsSelectors = this.jsSelectors = [];
  53. /* Method not implemented handlers */
  54. function installNewSelectors (newSelectors, targetClasses) {
  55. newSelectors.forEach(function (selector) {
  56. var jsSelector = st2js(selector);
  57. jsSelectors.push(jsSelector);
  58. var fn = createDnuHandler(selector);
  59. installMethodOfJsObject(nilAsClass.fn.prototype, jsSelector, fn);
  60. targetClasses.forEach(function (target) {
  61. installMethodOfJsObject(target.fn.prototype, jsSelector, fn);
  62. });
  63. });
  64. }
  65. this.installNewSelectors = installNewSelectors;
  66. /* Dnu handler method */
  67. function createDnuHandler (stSelector) {
  68. return function () {
  69. return globals.Message._selector_arguments_notUnderstoodBy_(
  70. stSelector, [].slice.call(arguments), this
  71. );
  72. };
  73. }
  74. installNewSelectors(selectors, []);
  75. }
  76. RuntimeClassesBrik.deps = ["runtimeSelectors", "behaviorals", "classConstruction", "runtimeMethods"];
  77. function RuntimeClassesBrik (brikz, st) {
  78. var jsSelectors = brikz.runtimeSelectors.jsSelectors;
  79. var installNewSelectors = brikz.runtimeSelectors.installNewSelectors;
  80. var installAmberMethodIntoAmberClass = brikz.runtimeMethods.installAmberMethodIntoAmberClass;
  81. var traitsOrClasses = brikz.behaviorals.traitsOrClasses;
  82. var wireKlass = brikz.classConstruction.wireKlass;
  83. var detachedRootClasses = [];
  84. function detachClass (klass) {
  85. klass.detachedRoot = true;
  86. detachedRootClasses = traitsOrClasses.filter(function (klass) {
  87. return klass.detachedRoot;
  88. });
  89. initClass(klass);
  90. }
  91. st.detachClass = detachClass;
  92. emit.selectorsAdded = function (newSelectors) {
  93. installNewSelectors(newSelectors, detachedRootClasses);
  94. };
  95. /* Initialize a class in its class hierarchy. Handle both classes and
  96. metaclasses. */
  97. function initClassAndMetaclass (klass) {
  98. initClass(klass);
  99. initClass(klass.a$cls);
  100. }
  101. traitsOrClasses.forEach(function (traitOrClass) {
  102. if (!traitOrClass.trait) initClassAndMetaclass(traitOrClass);
  103. });
  104. function installStHooks () {
  105. emit.behavioralAdded = function (traitOrClass) {
  106. traitOrClass._enterOrganization();
  107. };
  108. emit.behavioralRemoved = function (traitOrClass) {
  109. traitOrClass._leaveOrganization();
  110. };
  111. }
  112. this.installStHooks = installStHooks;
  113. emit.classCreated = initClassAndMetaclass;
  114. emit.slotsChanged = initClassSlots;
  115. function initClass (klass) {
  116. wireKlass(klass);
  117. initClassMethods(klass);
  118. initClassSlots(klass);
  119. }
  120. function initClassMethods (klass) {
  121. if (klass.detachedRoot) {
  122. copySuperclass(klass);
  123. }
  124. installMethods(klass);
  125. }
  126. function initClassSlots (klass) {
  127. installIvarCompat(klass);
  128. }
  129. function copySuperclass (klass) {
  130. var myproto = klass.fn.prototype,
  131. superproto = klass.superclass.fn.prototype;
  132. jsSelectors.forEach(function (jsSelector) {
  133. installMethodOfJsObjectEx(myproto, jsSelector, superproto[jsSelector]);
  134. });
  135. }
  136. function installMethods (klass) {
  137. var methods = klass.methods;
  138. Object.keys(methods).forEach(function (selector) {
  139. installAmberMethodIntoAmberClass(methods[selector], klass);
  140. });
  141. }
  142. // TODO remove, ["@foo"] backward compatibility
  143. function installIvarCompat (klass) {
  144. var ivars = klass.slots;
  145. ivars.forEach(function (ivar) {
  146. Object.defineProperty(klass.fn.prototype, "@" + ivar, {
  147. get: function () {
  148. return this[ivar];
  149. },
  150. set: function (value) {
  151. return this[ivar] = value;
  152. },
  153. enumerable: false,
  154. configurable: true
  155. });
  156. });
  157. }
  158. /* Create an alias for an existing class */
  159. st.alias = function (traitOrClass, alias) {
  160. globals[alias] = traitOrClass;
  161. };
  162. /* Manually set the constructor of an existing Smalltalk klass, making it a detached root class. */
  163. st.setClassConstructor = this.setClassConstructor = function (klass, constructor) {
  164. klass.fn = constructor;
  165. detachClass(klass);
  166. klass.subclasses.forEach(reprotoFn(constructor));
  167. };
  168. function reprotoFn (constructor) {
  169. var prototype = constructor.prototype;
  170. return function (subclass) {
  171. Object.setPrototypeOf(subclass.fn.prototype, prototype);
  172. };
  173. }
  174. }
  175. FrameBindingBrik.deps = ["runtimeClasses"];
  176. function FrameBindingBrik (brikz, st) {
  177. var setClassConstructor = brikz.runtimeClasses.setClassConstructor;
  178. setClassConstructor(globals.Number, Number);
  179. setClassConstructor(globals.BlockClosure, Function);
  180. setClassConstructor(globals.Boolean, Boolean);
  181. setClassConstructor(globals.Date, Date);
  182. setClassConstructor(globals.String, String);
  183. setClassConstructor(globals.Array, Array);
  184. setClassConstructor(globals.RegularExpression, RegExp);
  185. setClassConstructor(globals.Error, Error);
  186. setClassConstructor(globals.Promise, Promise);
  187. this.__init__ = function () {
  188. st.alias(globals.Array, "OrderedCollection");
  189. st.alias(globals.Date, "Time");
  190. }
  191. }
  192. RuntimeMethodsBrik.deps = ["selectorConversion"];
  193. function RuntimeMethodsBrik (brikz, st) {
  194. var st2js = brikz.selectorConversion.st2js;
  195. function installAmberMethodIntoAmberClass (method, klass) {
  196. var jsSelector = method.jsSelector;
  197. if (!jsSelector) {
  198. jsSelector = method.jsSelector = st2js(method.selector);
  199. }
  200. return installMethodOfJsObjectEx(klass.fn.prototype, jsSelector, method.fn);
  201. }
  202. this.installAmberMethodIntoAmberClass = installAmberMethodIntoAmberClass;
  203. emit.behaviorMethodAdded = function (method, klass) {
  204. installAmberMethodIntoAmberClass(method, klass);
  205. propagateMethodChange(klass, method, klass);
  206. };
  207. emit.behaviorMethodRemoved = function (method, klass) {
  208. uninstallMethodOfJsObjectEx(klass.fn.prototype, method.jsSelector);
  209. propagateMethodChange(klass, method, null);
  210. };
  211. function installStHooks () {
  212. emit.methodReplaced = function (newMethod, oldMethod, traitOrBehavior) {
  213. traitOrBehavior._methodOrganizationEnter_andLeave_(newMethod, oldMethod);
  214. };
  215. }
  216. this.installStHooks = installStHooks;
  217. function propagateMethodChange (klass, method, exclude) {
  218. var selector = method.selector;
  219. var jsSelector = method.jsSelector;
  220. st.traverseClassTree(klass, function (subclass, sentinel) {
  221. if (subclass === exclude) return;
  222. if (subclass.methods[selector]) return sentinel;
  223. if (subclass.detachedRoot) {
  224. installMethodOfJsObjectEx(subclass.fn.prototype, jsSelector, subclass.superclass.fn.prototype[jsSelector]);
  225. }
  226. });
  227. }
  228. }
  229. function PrimitivesBrik (brikz, st) {
  230. /* Converts a JavaScript object to valid Smalltalk Object */
  231. st.readJSObject = function (js) {
  232. if (js == null) return null;
  233. else if (Array.isArray(js)) return js.map(st.readJSObject);
  234. else if (js.constructor !== Object) return js;
  235. var pairs = [];
  236. for (var i in js) {
  237. pairs.push(i, st.readJSObject(js[i]));
  238. }
  239. return globals.Dictionary._newFromPairs_(pairs);
  240. };
  241. /* Boolean assertion */
  242. st.assert = function (shouldBeBoolean) {
  243. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  244. else if (shouldBeBoolean != null && typeof shouldBeBoolean === "object") {
  245. shouldBeBoolean = shouldBeBoolean.valueOf();
  246. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  247. }
  248. globals.NonBooleanReceiver._signalOn_(shouldBeBoolean);
  249. };
  250. }
  251. RuntimeBrik.deps = ["selectorConversion", "runtimeClasses"];
  252. function RuntimeBrik (brikz, st) {
  253. var setClassConstructor = brikz.runtimeClasses.setClassConstructor;
  254. function SmalltalkMethodContext (home, setup) {
  255. // TODO lazy fill of .sendIdx
  256. this.sendIdx = {};
  257. // TODO very likely .senderContext, not .homeContext here
  258. this.homeContext = home;
  259. this.setup = setup;
  260. }
  261. // Fallbacks
  262. SmalltalkMethodContext.prototype.supercall = false;
  263. SmalltalkMethodContext.prototype.locals = Object.freeze({});
  264. SmalltalkMethodContext.prototype.receiver = null;
  265. SmalltalkMethodContext.prototype.selector = null;
  266. SmalltalkMethodContext.prototype.outerContext = null;
  267. SmalltalkMethodContext.prototype.index = 0;
  268. declareJsMethod(SmalltalkMethodContext.prototype, "fill");
  269. declareJsMethod(SmalltalkMethodContext.prototype, "fillBlock");
  270. SmalltalkMethodContext.prototype.fill = function (receiver, selector, locals) {
  271. this.receiver = receiver;
  272. this.selector = selector;
  273. if (locals != null) this.locals = locals;
  274. if (this.homeContext) {
  275. this.homeContext.evaluatedSelector = selector;
  276. }
  277. };
  278. SmalltalkMethodContext.prototype.fillBlock = function (locals, ctx, index) {
  279. if (locals != null) this.locals = locals;
  280. this.outerContext = ctx;
  281. if (index) this.index = index;
  282. };
  283. setClassConstructor(globals.MethodContext, SmalltalkMethodContext);
  284. /* This is the current call context object.
  285. In Smalltalk code, it is accessible just by using 'thisContext' variable.
  286. In JS code, use api.getThisContext() (see below).
  287. */
  288. var thisContext = null;
  289. /*
  290. Runs worker function so that error handler is not set up
  291. if there isn't one. This is accomplished by unconditional
  292. wrapping inside a context of a simulated `nil seamlessDoIt` call,
  293. which then stops error handler setup (see st.withContext above).
  294. The effect is, $core.seamless(fn)'s exceptions are not
  295. handed into ST error handler and caller should process them.
  296. */
  297. st.seamless = function (worker) {
  298. var oldContext = thisContext;
  299. thisContext = new SmalltalkMethodContext(thisContext, function (ctx) {
  300. ctx.fill(null, "seamlessDoIt", {}, globals.UndefinedObject);
  301. });
  302. var result = worker(thisContext);
  303. thisContext = oldContext;
  304. return result;
  305. };
  306. function resultWithErrorHandling (worker) {
  307. try {
  308. return worker(thisContext);
  309. } catch (error) {
  310. globals.ErrorHandler._handleError_(error);
  311. thisContext = null;
  312. // Rethrow the error in any case.
  313. throw error;
  314. }
  315. }
  316. /*
  317. Standard way to run within context.
  318. Sets up error handler if entering first ST context in a stack.
  319. */
  320. st.withContext = function (worker, setup) {
  321. var oldContext = thisContext;
  322. thisContext = new SmalltalkMethodContext(thisContext, setup);
  323. var result = oldContext == null ? resultWithErrorHandling(worker) : worker(thisContext);
  324. thisContext = oldContext;
  325. return result;
  326. };
  327. /* Handle thisContext pseudo variable */
  328. st.getThisContext = function () {
  329. if (!thisContext) return null;
  330. for (var frame = thisContext; frame; frame = frame.homeContext) {
  331. frame.setup(frame);
  332. }
  333. return thisContext;
  334. };
  335. }
  336. MessageSendBrik.deps = ["selectorConversion"];
  337. function MessageSendBrik (brikz, st) {
  338. /* Send message programmatically. Used to implement #perform: & Co. */
  339. st.send2 = function (self, selector, args, klass) {
  340. var method = klass ? klass.fn.prototype[st.st2js(selector)] : self.a$cls && self[st.st2js(selector)];
  341. return method != null ?
  342. method.apply(self, args || []) :
  343. globals.Message._selector_arguments_notUnderstoodBy_(
  344. selector, [].slice.call(args), self.a$cls ? self : wrapJavaScript(self)
  345. );
  346. };
  347. function wrapJavaScript (o) {
  348. return globals.JSObjectProxy._on_(o);
  349. }
  350. st.wrapJavaScript = wrapJavaScript;
  351. /* If the object property is a function, then call it, except if it starts with
  352. an uppercase character (we probably want to answer the function itself in this
  353. case and send it #new from Amber).
  354. */
  355. st.accessJavaScript = function (self, propertyName, args) {
  356. var propertyValue = self[propertyName];
  357. if (typeof propertyValue === "function" && !(args.length === 0 && /^[A-Z]/.test(propertyName)))
  358. return propertyValue.apply(self, args);
  359. switch (args.length) {
  360. case 0:
  361. return propertyValue;
  362. case 1:
  363. self[propertyName] = args[0];
  364. return self;
  365. default:
  366. throw new Error("Cannot interpret " + propertyName + " with " + args.length + " arguments; field is a " + typeof propertyValue + ", not a function")
  367. }
  368. };
  369. }
  370. StartImageBrik.deps = ["runtimeClasses", "runtimeMethods"];
  371. function StartImageBrik (brikz, st) {
  372. this.run = function () {
  373. brikz.runtimeClasses.installStHooks();
  374. brikz.runtimeMethods.installStHooks();
  375. return globals.AmberBootstrapInitialization._run();
  376. };
  377. }
  378. /* Making smalltalk that can run */
  379. function configure (brikz) {
  380. brikz.runtimeSelectors = RuntimeSelectorsBrik;
  381. brikz.runtimeClasses = RuntimeClassesBrik;
  382. brikz.frameBinding = FrameBindingBrik;
  383. brikz.runtimeMethods = RuntimeMethodsBrik;
  384. brikz.messageSend = MessageSendBrik;
  385. brikz.runtime = RuntimeBrik;
  386. brikz.primitives = PrimitivesBrik;
  387. brikz.selectorConversion = SelectorConversionBrik;
  388. brikz.startImage = StartImageBrik;
  389. brikz();
  390. }
  391. return {configure: configure};
  392. }
  393. return RuntimeFactory;
  394. });