2
0

kernel-runtime.js 19 KB

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