2
0

kernel-runtime.js 19 KB

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