1
0

kernel-runtime.js 18 KB

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