kernel-runtime.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. RuntimeSelectorsBrik.deps = ["selectors", "selectorConversion", "smalltalkGlobals", "classes"];
  17. function RuntimeSelectorsBrik (brikz, st) {
  18. var selectors = brikz.selectors.selectors;
  19. var globals = brikz.smalltalkGlobals.globals;
  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 = ["event", "smalltalkGlobals", "runtimeSelectors", "behaviors", "classes", "runtimeMethods"];
  47. function RuntimeClassesBrik (brikz, st) {
  48. var globals = brikz.smalltalkGlobals.globals;
  49. var jsSelectors = brikz.runtimeSelectors.jsSelectors;
  50. var installNewSelectors = brikz.runtimeSelectors.installNewSelectors;
  51. var installMethod = brikz.runtimeMethods.installMethod;
  52. var traitsOrClasses = brikz.behaviors.traitsOrClasses;
  53. var wireKlass = brikz.classes.wireKlass;
  54. var installIvarCompat = brikz.classes.installIvarCompat;
  55. var emit = brikz.event.emit;
  56. var detachedRootClasses = [];
  57. function markClassDetachedRoot (klass) {
  58. klass.detachedRoot = true;
  59. detachedRootClasses = traitsOrClasses.filter(function (klass) {
  60. return klass.detachedRoot;
  61. });
  62. }
  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. markClassDetachedRoot(klass);
  123. klass.fn = constructor;
  124. installIvarCompat(klass);
  125. initClass(klass);
  126. };
  127. }
  128. FrameBindingBrik.deps = ["smalltalkGlobals", "runtimeClasses"];
  129. function FrameBindingBrik (brikz, st) {
  130. var globals = brikz.smalltalkGlobals.globals;
  131. var setClassConstructor = brikz.runtimeClasses.setClassConstructor;
  132. setClassConstructor(globals.Number, Number);
  133. setClassConstructor(globals.BlockClosure, Function);
  134. setClassConstructor(globals.Boolean, Boolean);
  135. setClassConstructor(globals.Date, Date);
  136. setClassConstructor(globals.String, String);
  137. setClassConstructor(globals.Array, Array);
  138. setClassConstructor(globals.RegularExpression, RegExp);
  139. setClassConstructor(globals.Error, Error);
  140. setClassConstructor(globals.Promise, Promise);
  141. this.__init__ = function () {
  142. st.alias(globals.Array, "OrderedCollection");
  143. st.alias(globals.Date, "Time");
  144. }
  145. }
  146. RuntimeMethodsBrik.deps = ["event", "selectorConversion"];
  147. function RuntimeMethodsBrik (brikz, st) {
  148. var st2js = brikz.selectorConversion.st2js;
  149. var emit = brikz.event.emit;
  150. function installMethod (method, klass) {
  151. var jsSelector = method.jsSelector;
  152. if (!jsSelector) {
  153. jsSelector = method.jsSelector = st2js(method.selector);
  154. }
  155. installJSMethod(klass.fn.prototype, jsSelector, method.fn);
  156. }
  157. this.installMethod = installMethod;
  158. emit.behaviorMethodAdded = function (method, klass) {
  159. installMethod(method, klass);
  160. propagateMethodChange(klass, method, klass);
  161. };
  162. emit.behaviorMethodRemoved = function (method, klass) {
  163. delete klass.fn.prototype[method.jsSelector];
  164. propagateMethodChange(klass, method, null);
  165. };
  166. function installStHooks () {
  167. emit.methodReplaced = function (newMethod, oldMethod, traitOrBehavior) {
  168. traitOrBehavior._methodOrganizationEnter_andLeave_(newMethod, oldMethod);
  169. };
  170. }
  171. this.installStHooks = installStHooks;
  172. function propagateMethodChange (klass, method, exclude) {
  173. var selector = method.selector;
  174. var jsSelector = method.jsSelector;
  175. st.traverseClassTree(klass, function (subclass, sentinel) {
  176. if (subclass === exclude) return;
  177. if (subclass.methods[selector]) return sentinel;
  178. if (subclass.detachedRoot) {
  179. installJSMethod(subclass.fn.prototype, jsSelector, subclass.superclass.fn.prototype[jsSelector]);
  180. }
  181. });
  182. }
  183. }
  184. PrimitivesBrik.deps = ["smalltalkGlobals"];
  185. function PrimitivesBrik (brikz, st) {
  186. var globals = brikz.smalltalkGlobals.globals;
  187. /* Converts a JavaScript object to valid Smalltalk Object */
  188. st.readJSObject = function (js) {
  189. if (js == null) return null;
  190. else if (Array.isArray(js)) return js.map(st.readJSObject);
  191. else if (js.constructor !== Object) return js;
  192. var pairs = [];
  193. for (var i in js) {
  194. pairs.push(i, st.readJSObject(js[i]));
  195. }
  196. return globals.Dictionary._newFromPairs_(pairs);
  197. };
  198. /* Boolean assertion */
  199. st.assert = function (shouldBeBoolean) {
  200. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  201. else if (shouldBeBoolean != null && typeof shouldBeBoolean === "object") {
  202. shouldBeBoolean = shouldBeBoolean.valueOf();
  203. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  204. }
  205. globals.NonBooleanReceiver._signalOn_(shouldBeBoolean);
  206. };
  207. }
  208. RuntimeBrik.deps = ["selectorConversion", "smalltalkGlobals", "runtimeClasses"];
  209. function RuntimeBrik (brikz, st) {
  210. var globals = brikz.smalltalkGlobals.globals;
  211. var setClassConstructor = brikz.runtimeClasses.setClassConstructor;
  212. function SmalltalkMethodContext (home, setup) {
  213. // TODO lazy fill of .sendIdx
  214. this.sendIdx = {};
  215. // TODO very likely .senderContext, not .homeContext here
  216. this.homeContext = home;
  217. this.setup = setup;
  218. }
  219. // Fallbacks
  220. SmalltalkMethodContext.prototype.supercall = false;
  221. SmalltalkMethodContext.prototype.locals = Object.freeze({});
  222. SmalltalkMethodContext.prototype.receiver = null;
  223. SmalltalkMethodContext.prototype.selector = null;
  224. SmalltalkMethodContext.prototype.outerContext = null;
  225. SmalltalkMethodContext.prototype.index = 0;
  226. defineMethod(SmalltalkMethodContext, "fill", function (receiver, selector, locals) {
  227. this.receiver = receiver;
  228. this.selector = selector;
  229. if (locals != null) this.locals = locals;
  230. if (this.homeContext) {
  231. this.homeContext.evaluatedSelector = selector;
  232. }
  233. });
  234. defineMethod(SmalltalkMethodContext, "fillBlock", function (locals, ctx, index) {
  235. if (locals != null) this.locals = locals;
  236. this.outerContext = ctx;
  237. if (index) this.index = index;
  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" && !(args.length === 0 && /^[A-Z]/.test(propertyName)))
  319. return propertyValue.apply(self, args);
  320. switch (args.length) {
  321. case 0:
  322. return propertyValue;
  323. case 1:
  324. self[propertyName] = args[0];
  325. return self;
  326. default:
  327. throw new Error("Cannot interpret " + propertyName + " with " + args.length + " arguments; field is a " + typeof propertyValue + ", not a function")
  328. }
  329. };
  330. }
  331. function SelectorConversionBrik (brikz, st) {
  332. var st2jsMemo = Object.create(null);
  333. /* Convert a Smalltalk selector into a JS selector */
  334. function st2js (string) {
  335. return '_' + string
  336. .replace(/:/g, '_')
  337. .replace(/[\&]/g, '_and')
  338. .replace(/[\|]/g, '_or')
  339. .replace(/[+]/g, '_plus')
  340. .replace(/-/g, '_minus')
  341. .replace(/[*]/g, '_star')
  342. .replace(/[\/]/g, '_slash')
  343. .replace(/[\\]/g, '_backslash')
  344. .replace(/[\~]/g, '_tild')
  345. .replace(/%/g, '_percent')
  346. .replace(/>/g, '_gt')
  347. .replace(/</g, '_lt')
  348. .replace(/=/g, '_eq')
  349. .replace(/,/g, '_comma')
  350. .replace(/[@]/g, '_at');
  351. };
  352. st.st2js = function (stSelector) {
  353. return st2jsMemo[stSelector] || st2js(stSelector);
  354. };
  355. this.st2js = function (stSelector) {
  356. return st2jsMemo[stSelector] || (st2jsMemo[stSelector] = st2js(stSelector));
  357. };
  358. /* Convert a string to a valid smalltalk selector.
  359. if you modify the following functions, also change st2js
  360. accordingly */
  361. st.js2st = function (selector) {
  362. if (selector.match(/^__/)) {
  363. return binaryJsToSt(selector);
  364. } else {
  365. return keywordJsToSt(selector);
  366. }
  367. };
  368. function keywordJsToSt (selector) {
  369. return selector.replace(/^_/, '').replace(/_/g, ':');
  370. }
  371. function binaryJsToSt (selector) {
  372. return selector
  373. .replace(/^_/, '')
  374. .replace(/_and/g, '&')
  375. .replace(/_or/g, '|')
  376. .replace(/_plus/g, '+')
  377. .replace(/_minus/g, '-')
  378. .replace(/_star/g, '*')
  379. .replace(/_slash/g, '/')
  380. .replace(/_backslash/g, '\\')
  381. .replace(/_tild/g, '~')
  382. .replace(/_percent/g, '%')
  383. .replace(/_gt/g, '>')
  384. .replace(/_lt/g, '<')
  385. .replace(/_eq/g, '=')
  386. .replace(/_comma/g, ',')
  387. .replace(/_at/g, '@');
  388. }
  389. st.st2prop = function (stSelector) {
  390. var colonPosition = stSelector.indexOf(':');
  391. return colonPosition === -1 ? stSelector : stSelector.slice(0, colonPosition);
  392. };
  393. }
  394. StartImageBrik.deps = ["smalltalkGlobals", "runtimeClasses", "runtimeMethods"];
  395. function StartImageBrik (brikz, st) {
  396. var globals = brikz.smalltalkGlobals.globals;
  397. this.run = function () {
  398. brikz.runtimeClasses.installStHooks();
  399. brikz.runtimeMethods.installStHooks();
  400. return globals.AmberBootstrapInitialization._run();
  401. };
  402. }
  403. /* Making smalltalk that can run */
  404. function configureWithRuntime (brikz) {
  405. brikz.runtimeSelectors = RuntimeSelectorsBrik;
  406. brikz.runtimeClasses = RuntimeClassesBrik;
  407. brikz.frameBinding = FrameBindingBrik;
  408. brikz.runtimeMethods = RuntimeMethodsBrik;
  409. brikz.messageSend = MessageSendBrik;
  410. brikz.runtime = RuntimeBrik;
  411. brikz.primitives = PrimitivesBrik;
  412. brikz.selectorConversion = SelectorConversionBrik;
  413. brikz.startImage = StartImageBrik;
  414. brikz();
  415. }
  416. return configureWithRuntime;
  417. });