kernel-runtime.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 RuntimeFactory (globals, emit) {
  17. RuntimeSelectorsBrik.deps = ["selectors", "selectorConversion", "classes"];
  18. function RuntimeSelectorsBrik (brikz, st) {
  19. var selectors = brikz.selectors.selectors;
  20. var nilAsClass = brikz.classes.nilAsClass;
  21. var st2js = brikz.selectorConversion.st2js;
  22. var jsSelectors = this.jsSelectors = [];
  23. /* Method not implemented handlers */
  24. function installNewSelectors (newSelectors, targetClasses) {
  25. newSelectors.forEach(function (selector) {
  26. var jsSelector = st2js(selector);
  27. jsSelectors.push(jsSelector);
  28. var fn = createDnuHandler(selector);
  29. installJSMethod(nilAsClass.fn.prototype, jsSelector, fn);
  30. targetClasses.forEach(function (target) {
  31. installJSMethod(target.fn.prototype, jsSelector, fn);
  32. });
  33. });
  34. }
  35. this.installNewSelectors = installNewSelectors;
  36. /* Dnu handler method */
  37. function createDnuHandler (stSelector) {
  38. return function () {
  39. return globals.Message._selector_arguments_notUnderstoodBy_(
  40. stSelector, [].slice.call(arguments), this
  41. );
  42. };
  43. }
  44. installNewSelectors(selectors, []);
  45. }
  46. RuntimeClassesBrik.deps = ["runtimeSelectors", "behaviors", "classes", "runtimeMethods"];
  47. function RuntimeClassesBrik (brikz, st) {
  48. var jsSelectors = brikz.runtimeSelectors.jsSelectors;
  49. var installNewSelectors = brikz.runtimeSelectors.installNewSelectors;
  50. var installMethod = brikz.runtimeMethods.installMethod;
  51. var traitsOrClasses = brikz.behaviors.traitsOrClasses;
  52. var wireKlass = brikz.classes.wireKlass;
  53. var installIvarCompat = brikz.classes.installIvarCompat;
  54. var detachedRootClasses = [];
  55. function detachClass (klass) {
  56. klass.detachedRoot = true;
  57. detachedRootClasses = traitsOrClasses.filter(function (klass) {
  58. return klass.detachedRoot;
  59. });
  60. initClass(klass);
  61. }
  62. st.detachClass = detachClass;
  63. emit.selectorsAdded = function (newSelectors) {
  64. installNewSelectors(newSelectors, detachedRootClasses);
  65. };
  66. /* Initialize a class in its class hierarchy. Handle both classes and
  67. metaclasses. */
  68. function initClassAndMetaclass (klass) {
  69. initClass(klass);
  70. if (klass.a$cls && !klass.meta) {
  71. initClass(klass.a$cls);
  72. }
  73. }
  74. traitsOrClasses.forEach(function (traitOrClass) {
  75. if (!traitOrClass.trait) initClassAndMetaclass(traitOrClass);
  76. });
  77. function installStHooks () {
  78. emit.classAdded = function (klass) {
  79. initClassAndMetaclass(klass);
  80. klass._enterOrganization();
  81. };
  82. emit.traitAdded = function (trait) {
  83. trait._enterOrganization();
  84. };
  85. emit.classRemoved = function (klass) {
  86. klass._leaveOrganization();
  87. };
  88. emit.traitRemoved = function (trait) {
  89. trait._leaveOrganization();
  90. };
  91. }
  92. this.installStHooks = installStHooks;
  93. emit.classAdded = function (klass) {
  94. initClassAndMetaclass(klass);
  95. };
  96. function initClass (klass) {
  97. wireKlass(klass);
  98. if (klass.detachedRoot) {
  99. copySuperclass(klass);
  100. }
  101. installMethods(klass);
  102. }
  103. function copySuperclass (klass) {
  104. var myproto = klass.fn.prototype,
  105. superproto = klass.superclass.fn.prototype;
  106. jsSelectors.forEach(function (jsSelector) {
  107. installJSMethod(myproto, jsSelector, superproto[jsSelector]);
  108. });
  109. }
  110. function installMethods (klass) {
  111. var methods = klass.methods;
  112. Object.keys(methods).forEach(function (selector) {
  113. installMethod(methods[selector], klass);
  114. });
  115. }
  116. /* Create an alias for an existing class */
  117. st.alias = function (traitOrClass, alias) {
  118. globals[alias] = traitOrClass;
  119. };
  120. /* Manually set the constructor of an existing Smalltalk klass, making it a detached root class. */
  121. st.setClassConstructor = this.setClassConstructor = function (klass, constructor) {
  122. klass.fn = constructor;
  123. detachClass(klass);
  124. installIvarCompat(klass);
  125. klass.subclasses.forEach(reprotoFn(constructor));
  126. };
  127. function reprotoFn (constructor) {
  128. var prototype = constructor.prototype;
  129. return function (subclass) {
  130. Object.setPrototypeOf(subclass.fn.prototype, prototype);
  131. };
  132. }
  133. }
  134. FrameBindingBrik.deps = ["runtimeClasses"];
  135. function FrameBindingBrik (brikz, st) {
  136. var setClassConstructor = brikz.runtimeClasses.setClassConstructor;
  137. setClassConstructor(globals.Number, Number);
  138. setClassConstructor(globals.BlockClosure, Function);
  139. setClassConstructor(globals.Boolean, Boolean);
  140. setClassConstructor(globals.Date, Date);
  141. setClassConstructor(globals.String, String);
  142. setClassConstructor(globals.Array, Array);
  143. setClassConstructor(globals.RegularExpression, RegExp);
  144. setClassConstructor(globals.Error, Error);
  145. setClassConstructor(globals.Promise, Promise);
  146. this.__init__ = function () {
  147. st.alias(globals.Array, "OrderedCollection");
  148. st.alias(globals.Date, "Time");
  149. }
  150. }
  151. RuntimeMethodsBrik.deps = ["selectorConversion"];
  152. function RuntimeMethodsBrik (brikz, st) {
  153. var st2js = brikz.selectorConversion.st2js;
  154. function installMethod (method, klass) {
  155. var jsSelector = method.jsSelector;
  156. if (!jsSelector) {
  157. jsSelector = method.jsSelector = st2js(method.selector);
  158. }
  159. installJSMethod(klass.fn.prototype, jsSelector, method.fn);
  160. }
  161. this.installMethod = installMethod;
  162. emit.behaviorMethodAdded = function (method, klass) {
  163. installMethod(method, klass);
  164. propagateMethodChange(klass, method, klass);
  165. };
  166. emit.behaviorMethodRemoved = function (method, klass) {
  167. delete klass.fn.prototype[method.jsSelector];
  168. propagateMethodChange(klass, method, null);
  169. };
  170. function installStHooks () {
  171. emit.methodReplaced = function (newMethod, oldMethod, traitOrBehavior) {
  172. traitOrBehavior._methodOrganizationEnter_andLeave_(newMethod, oldMethod);
  173. };
  174. }
  175. this.installStHooks = installStHooks;
  176. function propagateMethodChange (klass, method, exclude) {
  177. var selector = method.selector;
  178. var jsSelector = method.jsSelector;
  179. st.traverseClassTree(klass, function (subclass, sentinel) {
  180. if (subclass === exclude) return;
  181. if (subclass.methods[selector]) return sentinel;
  182. if (subclass.detachedRoot) {
  183. installJSMethod(subclass.fn.prototype, jsSelector, subclass.superclass.fn.prototype[jsSelector]);
  184. }
  185. });
  186. }
  187. }
  188. function PrimitivesBrik (brikz, st) {
  189. /* Converts a JavaScript object to valid Smalltalk Object */
  190. st.readJSObject = function (js) {
  191. if (js == null) return null;
  192. else if (Array.isArray(js)) return js.map(st.readJSObject);
  193. else if (js.constructor !== Object) return js;
  194. var pairs = [];
  195. for (var i in js) {
  196. pairs.push(i, st.readJSObject(js[i]));
  197. }
  198. return globals.Dictionary._newFromPairs_(pairs);
  199. };
  200. /* Boolean assertion */
  201. st.assert = function (shouldBeBoolean) {
  202. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  203. else if (shouldBeBoolean != null && typeof shouldBeBoolean === "object") {
  204. shouldBeBoolean = shouldBeBoolean.valueOf();
  205. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  206. }
  207. globals.NonBooleanReceiver._signalOn_(shouldBeBoolean);
  208. };
  209. }
  210. RuntimeBrik.deps = ["selectorConversion", "runtimeClasses"];
  211. function RuntimeBrik (brikz, st) {
  212. var setClassConstructor = brikz.runtimeClasses.setClassConstructor;
  213. function SmalltalkMethodContext (home, setup) {
  214. // TODO lazy fill of .sendIdx
  215. this.sendIdx = {};
  216. // TODO very likely .senderContext, not .homeContext here
  217. this.homeContext = home;
  218. this.setup = setup;
  219. }
  220. // Fallbacks
  221. SmalltalkMethodContext.prototype.supercall = false;
  222. SmalltalkMethodContext.prototype.locals = Object.freeze({});
  223. SmalltalkMethodContext.prototype.receiver = null;
  224. SmalltalkMethodContext.prototype.selector = null;
  225. SmalltalkMethodContext.prototype.outerContext = null;
  226. SmalltalkMethodContext.prototype.index = 0;
  227. defineMethod(SmalltalkMethodContext, "fill", function (receiver, selector, locals) {
  228. this.receiver = receiver;
  229. this.selector = selector;
  230. if (locals != null) this.locals = locals;
  231. if (this.homeContext) {
  232. this.homeContext.evaluatedSelector = selector;
  233. }
  234. });
  235. defineMethod(SmalltalkMethodContext, "fillBlock", function (locals, ctx, index) {
  236. if (locals != null) this.locals = locals;
  237. this.outerContext = ctx;
  238. if (index) this.index = index;
  239. });
  240. setClassConstructor(globals.MethodContext, SmalltalkMethodContext);
  241. /* This is the current call context object.
  242. In Smalltalk code, it is accessible just by using 'thisContext' variable.
  243. In JS code, use api.getThisContext() (see below).
  244. */
  245. var thisContext = null;
  246. /*
  247. Runs worker function so that error handler is not set up
  248. if there isn't one. This is accomplished by unconditional
  249. wrapping inside a context of a simulated `nil seamlessDoIt` call,
  250. which then stops error handler setup (see st.withContext above).
  251. The effect is, $core.seamless(fn)'s exceptions are not
  252. handed into ST error handler and caller should process them.
  253. */
  254. st.seamless = function (worker) {
  255. var oldContext = thisContext;
  256. thisContext = new SmalltalkMethodContext(thisContext, function (ctx) {
  257. ctx.fill(null, "seamlessDoIt", {}, globals.UndefinedObject);
  258. });
  259. var result = worker(thisContext);
  260. thisContext = oldContext;
  261. return result;
  262. };
  263. function resultWithErrorHandling (worker) {
  264. try {
  265. return worker(thisContext);
  266. } catch (error) {
  267. globals.ErrorHandler._handleError_(error);
  268. thisContext = null;
  269. // Rethrow the error in any case.
  270. throw error;
  271. }
  272. }
  273. /*
  274. Standard way to run within context.
  275. Sets up error handler if entering first ST context in a stack.
  276. */
  277. st.withContext = function (worker, setup) {
  278. var oldContext = thisContext;
  279. thisContext = new SmalltalkMethodContext(thisContext, setup);
  280. var result = oldContext == null ? resultWithErrorHandling(worker) : worker(thisContext);
  281. thisContext = oldContext;
  282. return result;
  283. };
  284. /* Handle thisContext pseudo variable */
  285. st.getThisContext = function () {
  286. if (!thisContext) return null;
  287. for (var frame = thisContext; frame; frame = frame.homeContext) {
  288. frame.setup(frame);
  289. }
  290. return thisContext;
  291. };
  292. }
  293. MessageSendBrik.deps = ["selectorConversion"];
  294. function MessageSendBrik (brikz, st) {
  295. /* Send message programmatically. Used to implement #perform: & Co. */
  296. st.send2 = function (self, selector, args, klass) {
  297. var method = klass ? klass.fn.prototype[st.st2js(selector)] : self.a$cls && self[st.st2js(selector)];
  298. return method != null ?
  299. method.apply(self, args || []) :
  300. globals.Message._selector_arguments_notUnderstoodBy_(
  301. selector, [].slice.call(args), self.a$cls ? self : wrapJavaScript(self)
  302. );
  303. };
  304. function wrapJavaScript (o) {
  305. return globals.JSObjectProxy._on_(o);
  306. }
  307. st.wrapJavaScript = wrapJavaScript;
  308. /* If the object property is a function, then call it, except if it starts with
  309. an uppercase character (we probably want to answer the function itself in this
  310. case and send it #new from Amber).
  311. */
  312. st.accessJavaScript = function (self, propertyName, args) {
  313. var propertyValue = self[propertyName];
  314. if (typeof propertyValue === "function" && !(args.length === 0 && /^[A-Z]/.test(propertyName)))
  315. return propertyValue.apply(self, args);
  316. switch (args.length) {
  317. case 0:
  318. return propertyValue;
  319. case 1:
  320. self[propertyName] = args[0];
  321. return self;
  322. default:
  323. throw new Error("Cannot interpret " + propertyName + " with " + args.length + " arguments; field is a " + typeof propertyValue + ", not a function")
  324. }
  325. };
  326. }
  327. function SelectorConversionBrik (brikz, st) {
  328. var st2jsMemo = Object.create(null);
  329. /* Convert a Smalltalk selector into a JS selector */
  330. function st2js (string) {
  331. return '_' + string
  332. .replace(/:/g, '_')
  333. .replace(/[\&]/g, '_and')
  334. .replace(/[\|]/g, '_or')
  335. .replace(/[+]/g, '_plus')
  336. .replace(/-/g, '_minus')
  337. .replace(/[*]/g, '_star')
  338. .replace(/[\/]/g, '_slash')
  339. .replace(/[\\]/g, '_backslash')
  340. .replace(/[\~]/g, '_tild')
  341. .replace(/%/g, '_percent')
  342. .replace(/>/g, '_gt')
  343. .replace(/</g, '_lt')
  344. .replace(/=/g, '_eq')
  345. .replace(/,/g, '_comma')
  346. .replace(/[@]/g, '_at');
  347. };
  348. st.st2js = function (stSelector) {
  349. return st2jsMemo[stSelector] || st2js(stSelector);
  350. };
  351. this.st2js = function (stSelector) {
  352. return st2jsMemo[stSelector] || (st2jsMemo[stSelector] = st2js(stSelector));
  353. };
  354. /* Convert a string to a valid smalltalk selector.
  355. if you modify the following functions, also change st2js
  356. accordingly */
  357. st.js2st = function (selector) {
  358. if (selector.match(/^__/)) {
  359. return binaryJsToSt(selector);
  360. } else {
  361. return keywordJsToSt(selector);
  362. }
  363. };
  364. function keywordJsToSt (selector) {
  365. return selector.replace(/^_/, '').replace(/_/g, ':');
  366. }
  367. function binaryJsToSt (selector) {
  368. return selector
  369. .replace(/^_/, '')
  370. .replace(/_and/g, '&')
  371. .replace(/_or/g, '|')
  372. .replace(/_plus/g, '+')
  373. .replace(/_minus/g, '-')
  374. .replace(/_star/g, '*')
  375. .replace(/_slash/g, '/')
  376. .replace(/_backslash/g, '\\')
  377. .replace(/_tild/g, '~')
  378. .replace(/_percent/g, '%')
  379. .replace(/_gt/g, '>')
  380. .replace(/_lt/g, '<')
  381. .replace(/_eq/g, '=')
  382. .replace(/_comma/g, ',')
  383. .replace(/_at/g, '@');
  384. }
  385. st.st2prop = function (stSelector) {
  386. var colonPosition = stSelector.indexOf(':');
  387. return colonPosition === -1 ? stSelector : stSelector.slice(0, colonPosition);
  388. };
  389. }
  390. StartImageBrik.deps = ["runtimeClasses", "runtimeMethods"];
  391. function StartImageBrik (brikz, st) {
  392. this.run = function () {
  393. brikz.runtimeClasses.installStHooks();
  394. brikz.runtimeMethods.installStHooks();
  395. return globals.AmberBootstrapInitialization._run();
  396. };
  397. }
  398. /* Making smalltalk that can run */
  399. function configure (brikz) {
  400. brikz.runtimeSelectors = RuntimeSelectorsBrik;
  401. brikz.runtimeClasses = RuntimeClassesBrik;
  402. brikz.frameBinding = FrameBindingBrik;
  403. brikz.runtimeMethods = RuntimeMethodsBrik;
  404. brikz.messageSend = MessageSendBrik;
  405. brikz.runtime = RuntimeBrik;
  406. brikz.primitives = PrimitivesBrik;
  407. brikz.selectorConversion = SelectorConversionBrik;
  408. brikz.startImage = StartImageBrik;
  409. brikz();
  410. }
  411. return {configure: configure};
  412. }
  413. return RuntimeFactory;
  414. });