1
0

kernel-runtime.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 emit = brikz.event.emit;
  55. var detachedRootClasses = [];
  56. function markClassDetachedRoot (klass) {
  57. klass.detachedRoot = true;
  58. detachedRootClasses = traitsOrClasses.filter(function (klass) {
  59. return klass.detachedRoot;
  60. });
  61. }
  62. emit.selectorsAdded = function (newSelectors) {
  63. installNewSelectors(newSelectors, detachedRootClasses);
  64. };
  65. /* Initialize a class in its class hierarchy. Handle both classes and
  66. metaclasses. */
  67. function initClassAndMetaclass (klass) {
  68. initClass(klass);
  69. if (klass.a$cls && !klass.meta) {
  70. initClass(klass.a$cls);
  71. }
  72. }
  73. traitsOrClasses.forEach(function (traitOrClass) {
  74. if (!traitOrClass.trait) initClassAndMetaclass(traitOrClass);
  75. });
  76. emit.classAdded = function (klass) {
  77. initClassAndMetaclass(klass);
  78. klass._enterOrganization();
  79. };
  80. emit.traitAdded = function (trait) {
  81. trait._enterOrganization();
  82. };
  83. emit.classRemoved = function (klass) {
  84. klass._leaveOrganization();
  85. };
  86. emit.traitRemoved = function (trait) {
  87. trait._leaveOrganization();
  88. };
  89. function initClass (klass) {
  90. wireKlass(klass);
  91. if (klass.detachedRoot) {
  92. copySuperclass(klass);
  93. }
  94. installMethods(klass);
  95. }
  96. function copySuperclass (klass) {
  97. var myproto = klass.fn.prototype,
  98. superproto = klass.superclass.fn.prototype;
  99. jsSelectors.forEach(function (jsSelector) {
  100. installJSMethod(myproto, jsSelector, superproto[jsSelector]);
  101. });
  102. }
  103. function installMethods (klass) {
  104. var methods = klass.methods;
  105. Object.keys(methods).forEach(function (selector) {
  106. installMethod(methods[selector], klass);
  107. });
  108. }
  109. /* Create an alias for an existing class */
  110. st.alias = function (traitOrClass, alias) {
  111. globals[alias] = traitOrClass;
  112. };
  113. /* Manually set the constructor of an existing Smalltalk klass, making it a detached root class. */
  114. st.setClassConstructor = this.setClassConstructor = function (klass, constructor) {
  115. markClassDetachedRoot(klass);
  116. klass.fn = constructor;
  117. initClass(klass);
  118. };
  119. }
  120. FrameBindingBrik.deps = ["smalltalkGlobals", "runtimeClasses"];
  121. function FrameBindingBrik (brikz, st) {
  122. var globals = brikz.smalltalkGlobals.globals;
  123. var setClassConstructor = brikz.runtimeClasses.setClassConstructor;
  124. setClassConstructor(globals.Number, Number);
  125. setClassConstructor(globals.BlockClosure, Function);
  126. setClassConstructor(globals.Boolean, Boolean);
  127. setClassConstructor(globals.Date, Date);
  128. setClassConstructor(globals.String, String);
  129. setClassConstructor(globals.Array, Array);
  130. setClassConstructor(globals.RegularExpression, RegExp);
  131. setClassConstructor(globals.Error, Error);
  132. setClassConstructor(globals.Promise, Promise);
  133. this.__init__ = function () {
  134. st.alias(globals.Array, "OrderedCollection");
  135. st.alias(globals.Date, "Time");
  136. }
  137. }
  138. RuntimeMethodsBrik.deps = ["event", "selectorConversion"];
  139. function RuntimeMethodsBrik (brikz, st) {
  140. var st2js = brikz.selectorConversion.st2js;
  141. var emit = brikz.event.emit;
  142. function installMethod (method, klass) {
  143. var jsSelector = method.jsSelector;
  144. if (!jsSelector) {
  145. jsSelector = method.jsSelector = st2js(method.selector);
  146. }
  147. installJSMethod(klass.fn.prototype, jsSelector, method.fn);
  148. }
  149. this.installMethod = installMethod;
  150. emit.behaviorMethodAdded = function (method, klass) {
  151. installMethod(method, klass);
  152. propagateMethodChange(klass, method, klass);
  153. };
  154. emit.behaviorMethodRemoved = function (method, klass) {
  155. delete klass.fn.prototype[method.jsSelector];
  156. propagateMethodChange(klass, method, null);
  157. };
  158. emit.methodReplaced = function (newMethod, oldMethod, traitOrBehavior) {
  159. traitOrBehavior._methodOrganizationEnter_andLeave_(newMethod, oldMethod);
  160. };
  161. function propagateMethodChange (klass, method, exclude) {
  162. var selector = method.selector;
  163. var jsSelector = method.jsSelector;
  164. st.traverseClassTree(klass, function (subclass, sentinel) {
  165. if (subclass === exclude) return;
  166. if (subclass.methods[selector]) return sentinel;
  167. if (subclass.detachedRoot) {
  168. installJSMethod(subclass.fn.prototype, jsSelector, subclass.superclass.fn.prototype[jsSelector]);
  169. }
  170. });
  171. }
  172. }
  173. PrimitivesBrik.deps = ["smalltalkGlobals"];
  174. function PrimitivesBrik (brikz, st) {
  175. var globals = brikz.smalltalkGlobals.globals;
  176. /* Converts a JavaScript object to valid Smalltalk Object */
  177. st.readJSObject = function (js) {
  178. if (js == null) return null;
  179. else if (Array.isArray(js)) return js.map(st.readJSObject);
  180. else if (js.constructor !== Object) return js;
  181. var pairs = [];
  182. for (var i in js) {
  183. pairs.push(i, st.readJSObject(js[i]));
  184. }
  185. return globals.Dictionary._newFromPairs_(pairs);
  186. };
  187. /* Boolean assertion */
  188. st.assert = function (shouldBeBoolean) {
  189. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  190. else if (shouldBeBoolean != null && typeof shouldBeBoolean === "object") {
  191. shouldBeBoolean = shouldBeBoolean.valueOf();
  192. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  193. }
  194. globals.NonBooleanReceiver._signalOn_(shouldBeBoolean);
  195. };
  196. }
  197. RuntimeBrik.deps = ["selectorConversion", "smalltalkGlobals", "runtimeClasses"];
  198. function RuntimeBrik (brikz, st) {
  199. var globals = brikz.smalltalkGlobals.globals;
  200. var setClassConstructor = brikz.runtimeClasses.setClassConstructor;
  201. function SmalltalkMethodContext (home, setup) {
  202. // TODO lazy fill of .sendIdx
  203. this.sendIdx = {};
  204. // TODO very likely .senderContext, not .homeContext here
  205. this.homeContext = home;
  206. this.setup = setup;
  207. }
  208. // Fallbacks
  209. SmalltalkMethodContext.prototype.supercall = false;
  210. SmalltalkMethodContext.prototype.locals = Object.freeze({});
  211. SmalltalkMethodContext.prototype.receiver = null;
  212. SmalltalkMethodContext.prototype.selector = null;
  213. SmalltalkMethodContext.prototype.lookupClass = null;
  214. SmalltalkMethodContext.prototype.outerContext = null;
  215. SmalltalkMethodContext.prototype.index = 0;
  216. defineMethod(SmalltalkMethodContext, "fill", function (receiver, selector, locals, lookupClass) {
  217. this.receiver = receiver;
  218. this.selector = selector;
  219. if (locals != null) this.locals = locals;
  220. this.lookupClass = lookupClass;
  221. if (this.homeContext) {
  222. this.homeContext.evaluatedSelector = selector;
  223. }
  224. });
  225. defineMethod(SmalltalkMethodContext, "fillBlock", function (locals, ctx, index) {
  226. if (locals != null) this.locals = locals;
  227. this.outerContext = ctx;
  228. if (index) this.index = index;
  229. });
  230. defineMethod(SmalltalkMethodContext, "method", function () {
  231. var method;
  232. var lookup = this.lookupClass || this.receiver.a$cls;
  233. while (!method && lookup) {
  234. method = lookup.methods[st.js2st(this.selector)];
  235. lookup = lookup.superclass;
  236. }
  237. return method;
  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" && !/^[A-Z]/.test(propertyName)) {
  319. return propertyValue.apply(self, args || []);
  320. } else if (args.length === 0) {
  321. return propertyValue;
  322. } else {
  323. self[propertyName] = args[0];
  324. return self;
  325. }
  326. };
  327. }
  328. function SelectorConversionBrik (brikz, st) {
  329. var st2jsMemo = Object.create(null);
  330. /* Convert a Smalltalk selector into a JS selector */
  331. function st2js (string) {
  332. return '_' + string
  333. .replace(/:/g, '_')
  334. .replace(/[\&]/g, '_and')
  335. .replace(/[\|]/g, '_or')
  336. .replace(/[+]/g, '_plus')
  337. .replace(/-/g, '_minus')
  338. .replace(/[*]/g, '_star')
  339. .replace(/[\/]/g, '_slash')
  340. .replace(/[\\]/g, '_backslash')
  341. .replace(/[\~]/g, '_tild')
  342. .replace(/%/g, '_percent')
  343. .replace(/>/g, '_gt')
  344. .replace(/</g, '_lt')
  345. .replace(/=/g, '_eq')
  346. .replace(/,/g, '_comma')
  347. .replace(/[@]/g, '_at');
  348. };
  349. st.st2js = function (stSelector) {
  350. return st2jsMemo[stSelector] || st2js(stSelector);
  351. };
  352. this.st2js = function (stSelector) {
  353. return st2jsMemo[stSelector] || (st2jsMemo[stSelector] = st2js(stSelector));
  354. };
  355. /* Convert a string to a valid smalltalk selector.
  356. if you modify the following functions, also change st2js
  357. accordingly */
  358. st.js2st = function (selector) {
  359. if (selector.match(/^__/)) {
  360. return binaryJsToSt(selector);
  361. } else {
  362. return keywordJsToSt(selector);
  363. }
  364. };
  365. function keywordJsToSt (selector) {
  366. return selector.replace(/^_/, '').replace(/_/g, ':');
  367. }
  368. function binaryJsToSt (selector) {
  369. return selector
  370. .replace(/^_/, '')
  371. .replace(/_and/g, '&')
  372. .replace(/_or/g, '|')
  373. .replace(/_plus/g, '+')
  374. .replace(/_minus/g, '-')
  375. .replace(/_star/g, '*')
  376. .replace(/_slash/g, '/')
  377. .replace(/_backslash/g, '\\')
  378. .replace(/_tild/g, '~')
  379. .replace(/_percent/g, '%')
  380. .replace(/_gt/g, '>')
  381. .replace(/_lt/g, '<')
  382. .replace(/_eq/g, '=')
  383. .replace(/_comma/g, ',')
  384. .replace(/_at/g, '@');
  385. }
  386. st.st2prop = function (stSelector) {
  387. var colonPosition = stSelector.indexOf(':');
  388. return colonPosition === -1 ? stSelector : stSelector.slice(0, colonPosition);
  389. };
  390. }
  391. StartImageBrik.deps = ["smalltalkGlobals"];
  392. function StartImageBrik (brikz, st) {
  393. var globals = brikz.smalltalkGlobals.globals;
  394. this.run = function () {
  395. return globals.AmberBootstrapInitialization._run();
  396. };
  397. }
  398. /* Making smalltalk that can run */
  399. function configureWithRuntime (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.rebuild();
  410. }
  411. return configureWithRuntime;
  412. });