kernel-runtime.js 18 KB

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