1
0

kernel-runtime.js 18 KB

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