1
0

kernel-runtime.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. var detachedRootClasses = [];
  51. function markClassDetachedRoot(klass) {
  52. detachedRootClasses.addElement(klass);
  53. klass.detachedRoot = true;
  54. }
  55. this.detachedRootClasses = function () {
  56. return detachedRootClasses;
  57. };
  58. /* Initialize a class in its class hierarchy. Handle both classes and
  59. metaclasses. */
  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.
  247. In Smalltalk code, it is accessible just by using 'thisContext' variable.
  248. In JS code, use api.getThisContext() (see below).
  249. */
  250. var thisContext = null;
  251. st.withContext = function (worker, setup) {
  252. if (thisContext) {
  253. return inContext(worker, setup);
  254. } else {
  255. return inContextWithErrorHandling(worker, setup);
  256. }
  257. };
  258. /*
  259. Runs worker function so that error handler is not set up
  260. if there isn't one. This is accomplished by unconditional
  261. wrapping inside a context of a simulated `nil seamlessDoIt` call,
  262. which then stops error handler setup (see st.withContext above).
  263. The effect is, $core.seamless(fn)'s exceptions are not
  264. handed into ST error handler and caller should process them.
  265. */
  266. st.seamless = function (worker) {
  267. return inContext(worker, function (ctx) {
  268. ctx.fill(null, "seamlessDoIt", {}, globals.UndefinedObject);
  269. });
  270. };
  271. function inContextWithErrorHandling(worker, setup) {
  272. try {
  273. return inContext(worker, setup);
  274. } catch (error) {
  275. handleError(error);
  276. thisContext = null;
  277. // Rethrow the error in any case.
  278. error.amberHandled = true;
  279. throw error;
  280. }
  281. }
  282. function inContext(worker, setup) {
  283. var oldContext = thisContext;
  284. thisContext = new SmalltalkMethodContext(thisContext, setup);
  285. var result = worker(thisContext);
  286. thisContext = oldContext;
  287. return result;
  288. }
  289. /* Wrap a JavaScript exception in a Smalltalk Exception.
  290. In case of a RangeError, stub the stack after 100 contexts to
  291. avoid another RangeError later when the stack is manipulated. */
  292. function wrappedError(error) {
  293. var errorWrapper = globals.JavaScriptException._on_(error);
  294. // Add the error to the context, so it is visible in the stack
  295. try {
  296. errorWrapper._signal();
  297. } catch (ex) {
  298. }
  299. var context = st.getThisContext();
  300. if (isRangeError(error)) {
  301. stubContextStack(context);
  302. }
  303. errorWrapper._context_(context);
  304. return errorWrapper;
  305. }
  306. /* Stub the context stack after 100 contexts */
  307. function stubContextStack(context) {
  308. var currentContext = context;
  309. var contexts = 0;
  310. while (contexts < 100) {
  311. if (currentContext) {
  312. currentContext = currentContext.homeContext;
  313. }
  314. contexts++;
  315. }
  316. if (currentContext) {
  317. currentContext.homeContext = undefined;
  318. }
  319. }
  320. function isRangeError(error) {
  321. return error instanceof RangeError;
  322. }
  323. /* Handles Smalltalk errors. Triggers the registered ErrorHandler
  324. (See the Smalltalk class ErrorHandler and its subclasses */
  325. function handleError(error) {
  326. if (!error.smalltalkError) {
  327. error = wrappedError(error);
  328. }
  329. globals.ErrorHandler._handleError_(error);
  330. }
  331. /* Handle thisContext pseudo variable */
  332. st.getThisContext = function () {
  333. if (thisContext) {
  334. thisContext.init();
  335. return thisContext;
  336. } else {
  337. return null;
  338. }
  339. };
  340. }
  341. MessageSendBrik.deps = ["smalltalkGlobals", "selectorConversion", "root"];
  342. function MessageSendBrik(brikz, st) {
  343. var globals = brikz.smalltalkGlobals.globals;
  344. var nilAsReceiver = brikz.root.nilAsReceiver;
  345. /* Send message programmatically. Used to implement #perform: & Co. */
  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. Converts keyword-based selectors by using the first
  374. keyword only, but keeping all message arguments.
  375. Example:
  376. "self do: aBlock with: anObject" -> "self.do(aBlock, anObject)"
  377. Else try wrapping a JSObjectProxy around the receiver. */
  378. var propertyName = st.st2prop(stSelector);
  379. if (!(propertyName in receiver)) {
  380. return invokeDnuMethod(globals.JSObjectProxy._on_(receiver), stSelector, args);
  381. }
  382. return accessJavaScript(receiver, propertyName, args);
  383. }
  384. /* If the object property is a function, then call it, except if it starts with
  385. an uppercase character (we probably want to answer the function itself in this
  386. case and send it #new from Amber).
  387. */
  388. function accessJavaScript(receiver, propertyName, args) {
  389. var propertyValue = receiver[propertyName];
  390. if (typeof propertyValue === "function" && !/^[A-Z]/.test(propertyName)) {
  391. return propertyValue.apply(receiver, args || []);
  392. } else if (args.length > 0) {
  393. receiver[propertyName] = args[0];
  394. return receiver;
  395. } else {
  396. return propertyValue;
  397. }
  398. }
  399. st.accessJavaScript = accessJavaScript;
  400. this.messageNotUnderstood = messageNotUnderstood;
  401. }
  402. /* Making smalltalk that can run */
  403. function configureWithRuntime(brikz) {
  404. brikz.dnu = DNUBrik;
  405. brikz.manipulation = ManipulationBrik;
  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.rebuild();
  413. }
  414. return configureWithRuntime;
  415. });