2
0

kernel-runtime.js 19 KB

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