kernel-runtime.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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.outerContext = null;
  216. SmalltalkMethodContext.prototype.index = 0;
  217. defineMethod(SmalltalkMethodContext, "fill", function (receiver, selector, locals) {
  218. this.receiver = receiver;
  219. this.selector = selector;
  220. if (locals != null) this.locals = locals;
  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. setClassConstructor(globals.MethodContext, SmalltalkMethodContext);
  231. /* This is the current call context object.
  232. In Smalltalk code, it is accessible just by using 'thisContext' variable.
  233. In JS code, use api.getThisContext() (see below).
  234. */
  235. var thisContext = null;
  236. /*
  237. Runs worker function so that error handler is not set up
  238. if there isn't one. This is accomplished by unconditional
  239. wrapping inside a context of a simulated `nil seamlessDoIt` call,
  240. which then stops error handler setup (see st.withContext above).
  241. The effect is, $core.seamless(fn)'s exceptions are not
  242. handed into ST error handler and caller should process them.
  243. */
  244. st.seamless = function (worker) {
  245. var oldContext = thisContext;
  246. thisContext = new SmalltalkMethodContext(thisContext, function (ctx) {
  247. ctx.fill(null, "seamlessDoIt", {}, globals.UndefinedObject);
  248. });
  249. var result = worker(thisContext);
  250. thisContext = oldContext;
  251. return result;
  252. };
  253. function resultWithErrorHandling (worker) {
  254. try {
  255. return worker(thisContext);
  256. } catch (error) {
  257. globals.ErrorHandler._handleError_(error);
  258. thisContext = null;
  259. // Rethrow the error in any case.
  260. throw error;
  261. }
  262. }
  263. /*
  264. Standard way to run within context.
  265. Sets up error handler if entering first ST context in a stack.
  266. */
  267. st.withContext = function (worker, setup) {
  268. var oldContext = thisContext;
  269. thisContext = new SmalltalkMethodContext(thisContext, setup);
  270. var result = oldContext == null ? resultWithErrorHandling(worker) : worker(thisContext);
  271. thisContext = oldContext;
  272. return result;
  273. };
  274. /* Handle thisContext pseudo variable */
  275. st.getThisContext = function () {
  276. if (!thisContext) return null;
  277. for (var frame = thisContext; frame; frame = frame.homeContext) {
  278. frame.setup(frame);
  279. }
  280. return thisContext;
  281. };
  282. }
  283. MessageSendBrik.deps = ["smalltalkGlobals", "selectorConversion", "root"];
  284. function MessageSendBrik (brikz, st) {
  285. var globals = brikz.smalltalkGlobals.globals;
  286. var nilAsReceiver = brikz.root.nilAsReceiver;
  287. /* Send message programmatically. Used to implement #perform: & Co. */
  288. st.send2 = function (self, selector, args, klass) {
  289. if (self == null) {
  290. self = nilAsReceiver;
  291. }
  292. var method = klass ? klass.fn.prototype[st.st2js(selector)] : self.a$cls && self[st.st2js(selector)];
  293. return method != null ?
  294. method.apply(self, args || []) :
  295. globals.Message._selector_arguments_notUnderstoodBy_(
  296. selector, [].slice.call(args), self.a$cls ? self : wrapJavaScript(self)
  297. );
  298. };
  299. function wrapJavaScript (o) {
  300. return globals.JSObjectProxy._on_(o);
  301. }
  302. st.wrapJavaScript = wrapJavaScript;
  303. /* If the object property is a function, then call it, except if it starts with
  304. an uppercase character (we probably want to answer the function itself in this
  305. case and send it #new from Amber).
  306. */
  307. st.accessJavaScript = function (self, propertyName, args) {
  308. var propertyValue = self[propertyName];
  309. if (typeof propertyValue === "function" && !(args.length === 0 && /^[A-Z]/.test(propertyName)))
  310. return propertyValue.apply(self, args);
  311. switch (args.length) {
  312. case 0:
  313. return propertyValue;
  314. case 1:
  315. self[propertyName] = args[0];
  316. return self;
  317. default:
  318. throw new Error("Cannot interpret " + propertyName + " with " + args.length + " arguments; field is a " + typeof propertyValue + ", not a function")
  319. }
  320. };
  321. }
  322. function SelectorConversionBrik (brikz, st) {
  323. var st2jsMemo = Object.create(null);
  324. /* Convert a Smalltalk selector into a JS selector */
  325. function st2js (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. st.st2js = function (stSelector) {
  344. return st2jsMemo[stSelector] || st2js(stSelector);
  345. };
  346. this.st2js = function (stSelector) {
  347. return st2jsMemo[stSelector] || (st2jsMemo[stSelector] = st2js(stSelector));
  348. };
  349. /* Convert a string to a valid smalltalk selector.
  350. if you modify the following functions, also change st2js
  351. accordingly */
  352. st.js2st = function (selector) {
  353. if (selector.match(/^__/)) {
  354. return binaryJsToSt(selector);
  355. } else {
  356. return keywordJsToSt(selector);
  357. }
  358. };
  359. function keywordJsToSt (selector) {
  360. return selector.replace(/^_/, '').replace(/_/g, ':');
  361. }
  362. function binaryJsToSt (selector) {
  363. return selector
  364. .replace(/^_/, '')
  365. .replace(/_and/g, '&')
  366. .replace(/_or/g, '|')
  367. .replace(/_plus/g, '+')
  368. .replace(/_minus/g, '-')
  369. .replace(/_star/g, '*')
  370. .replace(/_slash/g, '/')
  371. .replace(/_backslash/g, '\\')
  372. .replace(/_tild/g, '~')
  373. .replace(/_percent/g, '%')
  374. .replace(/_gt/g, '>')
  375. .replace(/_lt/g, '<')
  376. .replace(/_eq/g, '=')
  377. .replace(/_comma/g, ',')
  378. .replace(/_at/g, '@');
  379. }
  380. st.st2prop = function (stSelector) {
  381. var colonPosition = stSelector.indexOf(':');
  382. return colonPosition === -1 ? stSelector : stSelector.slice(0, colonPosition);
  383. };
  384. }
  385. StartImageBrik.deps = ["smalltalkGlobals"];
  386. function StartImageBrik (brikz, st) {
  387. var globals = brikz.smalltalkGlobals.globals;
  388. this.run = function () {
  389. return globals.AmberBootstrapInitialization._run();
  390. };
  391. }
  392. /* Making smalltalk that can run */
  393. function configureWithRuntime (brikz) {
  394. brikz.runtimeSelectors = RuntimeSelectorsBrik;
  395. brikz.runtimeClasses = RuntimeClassesBrik;
  396. brikz.frameBinding = FrameBindingBrik;
  397. brikz.runtimeMethods = RuntimeMethodsBrik;
  398. brikz.messageSend = MessageSendBrik;
  399. brikz.runtime = RuntimeBrik;
  400. brikz.primitives = PrimitivesBrik;
  401. brikz.selectorConversion = SelectorConversionBrik;
  402. brikz.startImage = StartImageBrik;
  403. brikz();
  404. }
  405. return configureWithRuntime;
  406. });