kernel-runtime.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. //jshint eqnull:true
  2. define(['./kernel-goodies'], 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. 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. installMethodOfJsObject(myproto, jsSelector, superproto[jsSelector]);
  117. });
  118. }
  119. function installMethods (klass) {
  120. var methods = klass.methods;
  121. Object.keys(methods).forEach(function (selector) {
  122. installAmberMethodIntoAmberClass(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 installAmberMethodIntoAmberClass (method, klass) {
  164. var jsSelector = method.jsSelector;
  165. if (!jsSelector) {
  166. jsSelector = method.jsSelector = st2js(method.selector);
  167. }
  168. installMethodOfJsObject(klass.fn.prototype, jsSelector, method.fn);
  169. }
  170. this.installAmberMethodIntoAmberClass = installAmberMethodIntoAmberClass;
  171. emit.behaviorMethodAdded = function (method, klass) {
  172. installAmberMethodIntoAmberClass(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. installMethodOfJsObject(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. declareJsMethod(SmalltalkMethodContext.prototype, "fill");
  237. declareJsMethod(SmalltalkMethodContext.prototype, "fillBlock");
  238. SmalltalkMethodContext.prototype.fill = function (receiver, selector, locals) {
  239. this.receiver = receiver;
  240. this.selector = selector;
  241. if (locals != null) this.locals = locals;
  242. if (this.homeContext) {
  243. this.homeContext.evaluatedSelector = selector;
  244. }
  245. };
  246. SmalltalkMethodContext.prototype.fillBlock = function (locals, ctx, index) {
  247. if (locals != null) this.locals = locals;
  248. this.outerContext = ctx;
  249. if (index) this.index = index;
  250. };
  251. setClassConstructor(globals.MethodContext, SmalltalkMethodContext);
  252. /* This is the current call context object.
  253. In Smalltalk code, it is accessible just by using 'thisContext' variable.
  254. In JS code, use api.getThisContext() (see below).
  255. */
  256. var thisContext = null;
  257. /*
  258. Runs worker function so that error handler is not set up
  259. if there isn't one. This is accomplished by unconditional
  260. wrapping inside a context of a simulated `nil seamlessDoIt` call,
  261. which then stops error handler setup (see st.withContext above).
  262. The effect is, $core.seamless(fn)'s exceptions are not
  263. handed into ST error handler and caller should process them.
  264. */
  265. st.seamless = function (worker) {
  266. var oldContext = thisContext;
  267. thisContext = new SmalltalkMethodContext(thisContext, function (ctx) {
  268. ctx.fill(null, "seamlessDoIt", {}, globals.UndefinedObject);
  269. });
  270. var result = worker(thisContext);
  271. thisContext = oldContext;
  272. return result;
  273. };
  274. function resultWithErrorHandling (worker) {
  275. try {
  276. return worker(thisContext);
  277. } catch (error) {
  278. globals.ErrorHandler._handleError_(error);
  279. thisContext = null;
  280. // Rethrow the error in any case.
  281. throw error;
  282. }
  283. }
  284. /*
  285. Standard way to run within context.
  286. Sets up error handler if entering first ST context in a stack.
  287. */
  288. st.withContext = function (worker, setup) {
  289. var oldContext = thisContext;
  290. thisContext = new SmalltalkMethodContext(thisContext, setup);
  291. var result = oldContext == null ? resultWithErrorHandling(worker) : worker(thisContext);
  292. thisContext = oldContext;
  293. return result;
  294. };
  295. /* Handle thisContext pseudo variable */
  296. st.getThisContext = function () {
  297. if (!thisContext) return null;
  298. for (var frame = thisContext; frame; frame = frame.homeContext) {
  299. frame.setup(frame);
  300. }
  301. return thisContext;
  302. };
  303. }
  304. MessageSendBrik.deps = ["selectorConversion"];
  305. function MessageSendBrik (brikz, st) {
  306. /* Send message programmatically. Used to implement #perform: & Co. */
  307. st.send2 = function (self, selector, args, klass) {
  308. var method = klass ? klass.fn.prototype[st.st2js(selector)] : self.a$cls && self[st.st2js(selector)];
  309. return method != null ?
  310. method.apply(self, args || []) :
  311. globals.Message._selector_arguments_notUnderstoodBy_(
  312. selector, [].slice.call(args), self.a$cls ? self : wrapJavaScript(self)
  313. );
  314. };
  315. function wrapJavaScript (o) {
  316. return globals.JSObjectProxy._on_(o);
  317. }
  318. st.wrapJavaScript = wrapJavaScript;
  319. /* If the object property is a function, then call it, except if it starts with
  320. an uppercase character (we probably want to answer the function itself in this
  321. case and send it #new from Amber).
  322. */
  323. st.accessJavaScript = function (self, propertyName, args) {
  324. var propertyValue = self[propertyName];
  325. if (typeof propertyValue === "function" && !(args.length === 0 && /^[A-Z]/.test(propertyName)))
  326. return propertyValue.apply(self, args);
  327. switch (args.length) {
  328. case 0:
  329. return propertyValue;
  330. case 1:
  331. self[propertyName] = args[0];
  332. return self;
  333. default:
  334. throw new Error("Cannot interpret " + propertyName + " with " + args.length + " arguments; field is a " + typeof propertyValue + ", not a function")
  335. }
  336. };
  337. }
  338. StartImageBrik.deps = ["runtimeClasses", "runtimeMethods"];
  339. function StartImageBrik (brikz, st) {
  340. this.run = function () {
  341. brikz.runtimeClasses.installStHooks();
  342. brikz.runtimeMethods.installStHooks();
  343. return globals.AmberBootstrapInitialization._run();
  344. };
  345. }
  346. /* Making smalltalk that can run */
  347. function configure (brikz) {
  348. brikz.runtimeSelectors = RuntimeSelectorsBrik;
  349. brikz.runtimeClasses = RuntimeClassesBrik;
  350. brikz.frameBinding = FrameBindingBrik;
  351. brikz.runtimeMethods = RuntimeMethodsBrik;
  352. brikz.messageSend = MessageSendBrik;
  353. brikz.runtime = RuntimeBrik;
  354. brikz.primitives = PrimitivesBrik;
  355. brikz.selectorConversion = SelectorConversionBrik;
  356. brikz.startImage = StartImageBrik;
  357. brikz();
  358. }
  359. return {configure: configure};
  360. }
  361. return RuntimeFactory;
  362. });