kernel-runtime.js 17 KB

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