kernel-runtime.js 18 KB

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