kernel-runtime.js 18 KB

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