kernel-runtime.js 17 KB

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