kernel-runtime.js 18 KB

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