kernel-runtime.js 18 KB

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