kernel-runtime.js 18 KB

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