kernel-runtime.js 15 KB

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