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