kernel-runtime.js 18 KB

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