1
0

kernel-runtime.js 17 KB

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