kernel-runtime.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. //jshint eqnull:true
  2. define(function () {
  3. "use strict";
  4. DNUBrik.deps = ["selectors", "messageSend", "manipulation", "root"];
  5. function DNUBrik(brikz, st) {
  6. var selectorsBrik = brikz.selectors;
  7. var messageNotUnderstood = brikz.messageSend.messageNotUnderstood;
  8. var installJSMethod = brikz.manipulation.installJSMethod;
  9. var nilAsClass = brikz.root.nilAsClass;
  10. /* Method not implemented handlers */
  11. function makeDnuHandler(pair, targetClasses) {
  12. var jsSelector = pair.js;
  13. var fn = createHandler(pair.st);
  14. installJSMethod(nilAsClass.fn.prototype, jsSelector, fn);
  15. targetClasses.forEach(function (target) {
  16. installJSMethod(target.fn.prototype, jsSelector, fn);
  17. });
  18. }
  19. this.makeDnuHandler = makeDnuHandler;
  20. /* Dnu handler method */
  21. function createHandler(stSelector) {
  22. return function () {
  23. return messageNotUnderstood(this, stSelector, arguments);
  24. };
  25. }
  26. selectorsBrik.selectorPairs.forEach(function (pair) {
  27. makeDnuHandler(pair, []);
  28. });
  29. }
  30. function ManipulationBrik(brikz, st) {
  31. function installJSMethod(obj, jsSelector, fn) {
  32. Object.defineProperty(obj, jsSelector, {
  33. value: fn,
  34. enumerable: false, configurable: true, writable: true
  35. });
  36. }
  37. function installMethod(method, klass) {
  38. installJSMethod(klass.fn.prototype, method.jsSelector, method.fn);
  39. }
  40. this.installMethod = installMethod;
  41. this.installJSMethod = installJSMethod;
  42. }
  43. RuntimeClassesBrik.deps = ["selectors", "dnu", "classes", "manipulation"];
  44. function RuntimeClassesBrik(brikz, st) {
  45. var selectors = brikz.selectors;
  46. var classes = brikz.classes.classes;
  47. var wireKlass = brikz.classes.wireKlass;
  48. var installMethod = brikz.manipulation.installMethod;
  49. var installJSMethod = brikz.manipulation.installJSMethod;
  50. /* Initialize a class in its class hierarchy. Handle both classes and
  51. metaclasses. */
  52. var detachedRootClasses = [];
  53. function markClassDetachedRoot(klass) {
  54. detachedRootClasses.addElement(klass);
  55. klass.detachedRoot = true;
  56. }
  57. this.detachedRootClasses = function () {
  58. return detachedRootClasses;
  59. };
  60. function initClassAndMetaclass(klass) {
  61. initClass(klass);
  62. if (klass.klass && !klass.meta) {
  63. initClass(klass.klass);
  64. }
  65. }
  66. classes().forEach(initClassAndMetaclass);
  67. st._classAdded = initClassAndMetaclass;
  68. function initClass(klass) {
  69. wireKlass(klass);
  70. if (klass.detachedRoot) {
  71. copySuperclass(klass);
  72. }
  73. installMethods(klass);
  74. }
  75. function copySuperclass(klass) {
  76. var myproto = klass.fn.prototype,
  77. superproto = klass.superclass.fn.prototype;
  78. selectors.selectorPairs.forEach(function (selectorPair) {
  79. var jsSelector = selectorPair.js;
  80. installJSMethod(myproto, jsSelector, superproto[jsSelector]);
  81. });
  82. }
  83. function installMethods(klass) {
  84. var methods = klass.methods;
  85. Object.keys(methods).forEach(function (selector) {
  86. installMethod(methods[selector], klass);
  87. });
  88. }
  89. /* Manually set the constructor of an existing Smalltalk klass, making it a detached root class. */
  90. st.setClassConstructor = this.setClassConstructor = function (klass, constructor) {
  91. markClassDetachedRoot(klass);
  92. klass.fn = constructor;
  93. initClass(klass);
  94. };
  95. }
  96. FrameBindingBrik.deps=["globals", "runtimeClasses"];
  97. function FrameBindingBrik(brikz, st) {
  98. var globals = brikz.smalltalkGlobals.globals;
  99. var setClassConstructor = brikz.runtimeClasses.setClassConstructor;
  100. setClassConstructor(globals.Number, Number);
  101. setClassConstructor(globals.BlockClosure, Function);
  102. setClassConstructor(globals.Boolean, Boolean);
  103. setClassConstructor(globals.Date, Date);
  104. setClassConstructor(globals.String, String);
  105. setClassConstructor(globals.Array, Array);
  106. setClassConstructor(globals.RegularExpression, RegExp);
  107. setClassConstructor(globals.Error, Error);
  108. setClassConstructor(globals.Promise, Promise);
  109. }
  110. RuntimeMethodsBrik.deps = ["manipulation", "dnu", "runtimeClasses"];
  111. function RuntimeMethodsBrik(brikz, st) {
  112. var installMethod = brikz.manipulation.installMethod;
  113. var installJSMethod = brikz.manipulation.installJSMethod;
  114. var makeDnuHandler = brikz.dnu.makeDnuHandler;
  115. var detachedRootClasses = brikz.runtimeClasses.detachedRootClasses;
  116. st._methodAdded = function (method, klass) {
  117. installMethod(method, klass);
  118. propagateMethodChange(klass, method, klass);
  119. };
  120. st._selectorsAdded = function (newSelectors) {
  121. var targetClasses = detachedRootClasses();
  122. newSelectors.forEach(function (pair) {
  123. makeDnuHandler(pair, targetClasses);
  124. });
  125. };
  126. st._methodRemoved = function (method, klass) {
  127. delete klass.fn.prototype[method.jsSelector];
  128. propagateMethodChange(klass, method, null);
  129. };
  130. function propagateMethodChange(klass, method, exclude) {
  131. var selector = method.selector;
  132. var jsSelector = method.jsSelector;
  133. st.traverseClassTree(klass, function (subclass) {
  134. if (subclass != exclude) {
  135. initMethodInClass(subclass, selector, jsSelector);
  136. }
  137. });
  138. }
  139. function initMethodInClass(klass, selector, jsSelector) {
  140. if (klass.detachedRoot && !klass.methods[selector]) {
  141. installJSMethod(klass.fn.prototype, jsSelector, klass.superclass.fn.prototype[jsSelector]);
  142. }
  143. }
  144. }
  145. PrimitivesBrik.deps = ["smalltalkGlobals"];
  146. function PrimitivesBrik(brikz, st) {
  147. var globals = brikz.smalltalkGlobals.globals;
  148. var oid = 0;
  149. /* Unique ID number generator */
  150. st.nextId = function () {
  151. oid += 1;
  152. return oid;
  153. };
  154. /* Converts a JavaScript object to valid Smalltalk Object */
  155. st.readJSObject = function (js) {
  156. if (js == null)
  157. return null;
  158. var readObject = js.constructor === Object;
  159. var readArray = js.constructor === Array;
  160. var object = readObject ? globals.Dictionary._new() : readArray ? [] : js;
  161. for (var i in js) {
  162. if (readObject) {
  163. object._at_put_(i, st.readJSObject(js[i]));
  164. }
  165. if (readArray) {
  166. object[i] = st.readJSObject(js[i]);
  167. }
  168. }
  169. return object;
  170. };
  171. /* Boolean assertion */
  172. st.assert = function (shouldBeBoolean) {
  173. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  174. else if (shouldBeBoolean != null && typeof shouldBeBoolean === "object") {
  175. shouldBeBoolean = shouldBeBoolean.valueOf();
  176. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  177. }
  178. globals.NonBooleanReceiver._new()._object_(shouldBeBoolean)._signal();
  179. };
  180. /* List of all reserved words in JavaScript. They may not be used as variables
  181. in Smalltalk. */
  182. // list of reserved JavaScript keywords as of
  183. // http://es5.github.com/#x7.6.1.1
  184. // and
  185. // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.6.1
  186. st.reservedWords = ['break', 'case', 'catch', 'continue', 'debugger',
  187. 'default', 'delete', 'do', 'else', 'finally', 'for', 'function',
  188. 'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', 'throw',
  189. 'try', 'typeof', 'var', 'void', 'while', 'with',
  190. // Amber protected words: these should not be compiled as-is when in code
  191. 'arguments',
  192. // ES5: future use: http://es5.github.com/#x7.6.1.2
  193. 'class', 'const', 'enum', 'export', 'extends', 'import', 'super',
  194. // ES5: future use in strict mode
  195. 'implements', 'interface', 'let', 'package', 'private', 'protected',
  196. 'public', 'static', 'yield'];
  197. st.globalJsVariables = ['window', 'document', 'process', 'global'];
  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. this.sendIdx = {};
  205. this.homeContext = home;
  206. this.setup = setup || function () {
  207. };
  208. this.supercall = false;
  209. }
  210. // Fallbacks
  211. SmalltalkMethodContext.prototype.locals = {};
  212. SmalltalkMethodContext.prototype.receiver = null;
  213. SmalltalkMethodContext.prototype.selector = null;
  214. SmalltalkMethodContext.prototype.lookupClass = null;
  215. SmalltalkMethodContext.prototype.fill = function (receiver, selector, locals, lookupClass) {
  216. this.receiver = receiver;
  217. this.selector = selector;
  218. this.locals = locals || {};
  219. this.lookupClass = lookupClass;
  220. if (this.homeContext) {
  221. this.homeContext.evaluatedSelector = selector;
  222. }
  223. };
  224. SmalltalkMethodContext.prototype.fillBlock = function (locals, ctx, index) {
  225. this.locals = locals || {};
  226. this.outerContext = ctx;
  227. this.index = index || 0;
  228. };
  229. SmalltalkMethodContext.prototype.init = function () {
  230. var home = this.homeContext;
  231. if (home) {
  232. home.init();
  233. }
  234. this.setup(this);
  235. };
  236. SmalltalkMethodContext.prototype.method = function () {
  237. var method;
  238. var lookup = this.lookupClass || this.receiver.klass;
  239. while (!method && lookup) {
  240. method = lookup.methods[st.js2st(this.selector)];
  241. lookup = lookup.superclass;
  242. }
  243. return method;
  244. };
  245. setClassConstructor(globals.MethodContext, SmalltalkMethodContext);
  246. /* This is the current call context object. While it is publicly available,
  247. Use smalltalk.getThisContext() instead which will answer a safe copy of
  248. the current context */
  249. var thisContext = null;
  250. st.withContext = function (worker, setup) {
  251. if (thisContext) {
  252. return inContext(worker, setup);
  253. } else {
  254. return inContextWithErrorHandling(worker, setup);
  255. }
  256. };
  257. /*
  258. Runs worker function so that error handler is not set up
  259. if there isn't one. This is accomplished by unconditional
  260. wrapping inside a context of a simulated `nil seamlessDoIt` call,
  261. which then stops error handler setup (see st.withContext above).
  262. The effect is, $core.seamless(fn)'s exceptions are not
  263. handed into ST error handler and caller should process them.
  264. */
  265. st.seamless = function (worker) {
  266. return inContext(worker, function (ctx) {
  267. ctx.fill(null, "seamlessDoIt", {}, globals.UndefinedObject);
  268. });
  269. };
  270. function inContextWithErrorHandling(worker, setup) {
  271. try {
  272. return inContext(worker, setup);
  273. } catch (error) {
  274. handleError(error);
  275. thisContext = null;
  276. // Rethrow the error in any case.
  277. error.amberHandled = true;
  278. throw error;
  279. }
  280. }
  281. function inContext(worker, setup) {
  282. var oldContext = thisContext;
  283. thisContext = new SmalltalkMethodContext(thisContext, setup);
  284. var result = worker(thisContext);
  285. thisContext = oldContext;
  286. return result;
  287. }
  288. /* Wrap a JavaScript exception in a Smalltalk Exception.
  289. In case of a RangeError, stub the stack after 100 contexts to
  290. avoid another RangeError later when the stack is manipulated. */
  291. function wrappedError(error) {
  292. var errorWrapper = globals.JavaScriptException._on_(error);
  293. // Add the error to the context, so it is visible in the stack
  294. try {
  295. errorWrapper._signal();
  296. } catch (ex) {
  297. }
  298. var context = st.getThisContext();
  299. if (isRangeError(error)) {
  300. stubContextStack(context);
  301. }
  302. errorWrapper._context_(context);
  303. return errorWrapper;
  304. }
  305. /* Stub the context stack after 100 contexts */
  306. function stubContextStack(context) {
  307. var currentContext = context;
  308. var contexts = 0;
  309. while (contexts < 100) {
  310. if (currentContext) {
  311. currentContext = currentContext.homeContext;
  312. }
  313. contexts++;
  314. }
  315. if (currentContext) {
  316. currentContext.homeContext = undefined;
  317. }
  318. }
  319. function isRangeError(error) {
  320. return error instanceof RangeError;
  321. }
  322. /* Handles Smalltalk errors. Triggers the registered ErrorHandler
  323. (See the Smalltalk class ErrorHandler and its subclasses */
  324. function handleError(error) {
  325. if (!error.smalltalkError) {
  326. error = wrappedError(error);
  327. }
  328. globals.ErrorHandler._handleError_(error);
  329. }
  330. /* Handle thisContext pseudo variable */
  331. st.getThisContext = function () {
  332. if (thisContext) {
  333. thisContext.init();
  334. return thisContext;
  335. } else {
  336. return null;
  337. }
  338. };
  339. }
  340. MessageSendBrik.deps = ["smalltalkGlobals", "selectorConversion", "root"];
  341. function MessageSendBrik(brikz, st) {
  342. var globals = brikz.smalltalkGlobals.globals;
  343. var nilAsReceiver = brikz.root.nilAsReceiver;
  344. /* Handles unhandled errors during message sends */
  345. // simply send the message and handle #dnu:
  346. st.send2 = function (receiver, selector, args, klass) {
  347. var method, jsSelector = st.st2js(selector);
  348. if (receiver == null) {
  349. receiver = nilAsReceiver;
  350. }
  351. method = klass ? klass.fn.prototype[jsSelector] : receiver.klass && receiver[jsSelector];
  352. if (method) {
  353. return method.apply(receiver, args || []);
  354. } else {
  355. return messageNotUnderstood(receiver, selector, args);
  356. }
  357. };
  358. function invokeDnuMethod(receiver, stSelector, args) {
  359. return receiver._doesNotUnderstand_(
  360. globals.Message._new()
  361. ._selector_(stSelector)
  362. ._arguments_([].slice.call(args))
  363. );
  364. }
  365. /* Handles #dnu: *and* JavaScript method calls.
  366. if the receiver has no klass, we consider it a JS object (outside of the
  367. Amber system). Else assume that the receiver understands #doesNotUnderstand: */
  368. function messageNotUnderstood(receiver, stSelector, args) {
  369. if (receiver.klass != null && !receiver.allowJavaScriptCalls) {
  370. return invokeDnuMethod(receiver, stSelector, args);
  371. }
  372. /* Call a method of a JS object, or answer a property if it exists.
  373. Else try wrapping a JSObjectProxy around the receiver. */
  374. var propertyName = st.st2prop(stSelector);
  375. if (!(propertyName in receiver)) {
  376. return invokeDnuMethod(globals.JSObjectProxy._on_(receiver), stSelector, args);
  377. }
  378. return accessJavaScript(receiver, propertyName, args);
  379. }
  380. /* If the object property is a function, then call it, except if it starts with
  381. an uppercase character (we probably want to answer the function itself in this
  382. case and send it #new from Amber).
  383. Converts keyword-based selectors by using the first
  384. keyword only, but keeping all message arguments.
  385. Example:
  386. "self do: aBlock with: anObject" -> "self.do(aBlock, anObject)" */
  387. function accessJavaScript(receiver, propertyName, args) {
  388. var propertyValue = receiver[propertyName];
  389. if (typeof propertyValue === "function" && !/^[A-Z]/.test(propertyName)) {
  390. return propertyValue.apply(receiver, args || []);
  391. } else if (args.length > 0) {
  392. receiver[propertyName] = args[0];
  393. return receiver;
  394. } else {
  395. return propertyValue;
  396. }
  397. }
  398. st.accessJavaScript = accessJavaScript;
  399. this.messageNotUnderstood = messageNotUnderstood;
  400. }
  401. /* Making smalltalk that can run */
  402. function configureWithRuntime(brikz) {
  403. brikz.dnu = DNUBrik;
  404. brikz.manipulation = ManipulationBrik;
  405. brikz.runtimeClasses = RuntimeClassesBrik;
  406. brikz.frameBinding = FrameBindingBrik;
  407. brikz.runtimeMethods = RuntimeMethodsBrik;
  408. brikz.messageSend = MessageSendBrik;
  409. brikz.runtime = RuntimeBrik;
  410. brikz.primitives = PrimitivesBrik;
  411. brikz.rebuild();
  412. }
  413. return configureWithRuntime;
  414. });