2
0

boot.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. /* ====================================================================
  2. |
  3. | Amber Smalltalk
  4. | http://amber-lang.net
  5. |
  6. ======================================================================
  7. ======================================================================
  8. |
  9. | Copyright (c) 2010-2013
  10. | Nicolas Petton <petton.nicolas@gmail.com>
  11. |
  12. | Copyright (c) 2012-2013
  13. | The Amber team https://github.com/amber-smalltalk?tab=members
  14. | Amber contributors https://github.com/amber-smalltalk/amber/graphs/contributors
  15. |
  16. | Amber is released under the MIT license
  17. |
  18. | Permission is hereby granted, free of charge, to any person obtaining
  19. | a copy of this software and associated documentation files (the
  20. | 'Software'), to deal in the Software without restriction, including
  21. | without limitation the rights to use, copy, modify, merge, publish,
  22. | distribute, sublicense, and/or sell copies of the Software, and to
  23. | permit persons to whom the Software is furnished to do so, subject to
  24. | the following conditions:
  25. |
  26. | The above copyright notice and this permission notice shall be
  27. | included in all copies or substantial portions of the Software.
  28. |
  29. | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
  30. | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  31. | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  32. | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  33. | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  34. | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  35. | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  36. |
  37. ==================================================================== */
  38. define("amber_vm/boot", [ './browser-compatibility' ], function () {
  39. /* Reconfigurable micro composition system, https://github.com/amber-smalltalk/brikz */
  40. function Brikz(api, apiKey, initKey) {
  41. var brikz = this, backup = {};
  42. apiKey = apiKey || 'exports';
  43. initKey = initKey || '__init__';
  44. function mixin(src, target, what) {
  45. for (var keys = Object.keys(what||src), l=keys.length, i=0; i<l; ++i) {
  46. var value = src[keys[i]];
  47. if (typeof value !== "undefined") { target[keys[i]] = value; }
  48. }
  49. return target;
  50. }
  51. var d={value: null, enumerable: false, configurable: true, writable: true};
  52. Object.defineProperties(this, { ensure: d, rebuild: d });
  53. var exclude = mixin(this, {});
  54. this.rebuild = function () {
  55. Object.keys(backup).forEach(function (key) {
  56. mixin({}, api, (backup[key]||0)[apiKey]);
  57. });
  58. var oapi = mixin(api, {}), order = [], chk = {};
  59. brikz.ensure = function(key) {
  60. if (key in exclude) { return null; }
  61. var b = brikz[key], bak = backup[key];
  62. mixin({}, api, api);
  63. while (typeof b === "function") { b = new b(brikz, api, bak); }
  64. if (b && !chk[key]) { chk[key]=true; order.push(b); }
  65. if (b && !b[apiKey]) { b[apiKey] = mixin(api, {}); }
  66. return brikz[key] = b;
  67. };
  68. Object.keys(brikz).forEach(function (key) { brikz.ensure(key); });
  69. brikz.ensure = null;
  70. mixin(oapi, mixin({}, api, api));
  71. order.forEach(function(brik) { mixin(brik[apiKey] || {}, api); });
  72. order.forEach(function(brik) { brik[initKey] && brik[initKey](); });
  73. backup = mixin(brikz, {});
  74. };
  75. }
  76. /* Brikz end */
  77. function inherits(child, parent) {
  78. child.prototype = Object.create(parent.prototype, {
  79. constructor: { value: child,
  80. enumerable: false, configurable: true, writable: true }
  81. });
  82. return child;
  83. }
  84. var api = {};
  85. var brikz = new Brikz(api);
  86. function RootBrik(brikz, st) {
  87. /* Smalltalk foundational objects */
  88. /* SmalltalkRoot is the hidden root of the Amber hierarchy.
  89. All objects including `Object` inherit from SmalltalkRoot */
  90. function SmalltalkRoot() {}
  91. function SmalltalkProtoObject() {}
  92. inherits(SmalltalkProtoObject, SmalltalkRoot);
  93. function SmalltalkObject() {}
  94. inherits(SmalltalkObject, SmalltalkProtoObject);
  95. function SmalltalkNil() {}
  96. inherits(SmalltalkNil, SmalltalkObject);
  97. this.Object = SmalltalkObject;
  98. this.nil = new SmalltalkNil();
  99. // Hidden root class of the system.
  100. this.rootAsClass = {fn: SmalltalkRoot};
  101. this.__init__ = function () {
  102. st.addPackage("Kernel-Objects");
  103. st.addPackage("Kernel-Infrastructure");
  104. st.wrapClassName("ProtoObject", "Kernel-Objects", SmalltalkProtoObject, undefined, false);
  105. st.wrapClassName("Object", "Kernel-Objects", SmalltalkObject, st.ProtoObject, false);
  106. st.wrapClassName("UndefinedObject", "Kernel-Objects", SmalltalkNil, st.Object, false);
  107. };
  108. }
  109. function OrganizeBrik(brikz, st) {
  110. brikz.ensure("augments");
  111. var SmalltalkObject = brikz.ensure("root").Object;
  112. function SmalltalkOrganizer () {}
  113. function SmalltalkPackageOrganizer () {
  114. this.elements = [];
  115. }
  116. function SmalltalkClassOrganizer () {
  117. this.elements = [];
  118. }
  119. inherits(SmalltalkOrganizer, SmalltalkObject);
  120. inherits(SmalltalkPackageOrganizer, SmalltalkOrganizer);
  121. inherits(SmalltalkClassOrganizer, SmalltalkOrganizer);
  122. this.__init__ = function () {
  123. st.wrapClassName("Organizer", "Kernel-Infrastructure", SmalltalkOrganizer, st.Object, false);
  124. st.wrapClassName("PackageOrganizer", "Kernel-Infrastructure", SmalltalkPackageOrganizer, st.Organizer, false);
  125. st.wrapClassName("ClassOrganizer", "Kernel-Infrastructure", SmalltalkClassOrganizer, st.Organizer, false);
  126. };
  127. this.setupClassOrganization = function (klass) {
  128. klass.organization = new SmalltalkClassOrganizer();
  129. klass.organization.theClass = klass;
  130. };
  131. this.setupPackageOrganization = function (pkg) {
  132. pkg.organization = new SmalltalkPackageOrganizer();
  133. };
  134. this.addOrganizationElement = function (owner, element) {
  135. owner.organization.elements.addElement(element);
  136. };
  137. this.removeOrganizationElement = function (owner, element) {
  138. owner.organization.elements.removeElement(element);
  139. };
  140. }
  141. function DNUBrik(brikz, st) {
  142. brikz.ensure("selectorConversion");
  143. brikz.ensure("messageSend");
  144. var manip = brikz.ensure("manipulation");
  145. var rootAsClass = brikz.ensure("root").rootAsClass;
  146. /* Method not implemented handlers */
  147. var methods = [], checker = Object.create(null);
  148. this.selectors = [];
  149. this.get = function (string) {
  150. var index = this.selectors.indexOf(string);
  151. if(index !== -1) {
  152. return methods[index];
  153. }
  154. this.selectors.push(string);
  155. var selector = st.selector(string);
  156. checker[selector] = true;
  157. var method = {jsSelector: selector, fn: createHandler(selector)};
  158. methods.push(method);
  159. manip.installMethod(method, rootAsClass);
  160. return method;
  161. };
  162. this.isSelector = function (selector) {
  163. return checker[selector];
  164. };
  165. /* Dnu handler method */
  166. function createHandler(selector) {
  167. return function() {
  168. var args = Array.prototype.slice.call(arguments);
  169. return brikz.messageSend.messageNotUnderstood(this, selector, args);
  170. };
  171. }
  172. this.installHandlers = function (klass) {
  173. for(var i=0; i<methods.length; i++) {
  174. manip.installMethodIfAbsent(methods[i], klass);
  175. }
  176. };
  177. }
  178. function ClassInitBrik(brikz, st) {
  179. var dnu = brikz.ensure("dnu");
  180. var manip = brikz.ensure("manipulation");
  181. var nil = brikz.ensure("root").nil;
  182. /* Initialize a class in its class hierarchy. Handle both classes and
  183. metaclasses. */
  184. st.init = function(klass) {
  185. st.initClass(klass);
  186. if(klass.klass && !klass.meta) {
  187. st.initClass(klass.klass);
  188. }
  189. };
  190. st.initClass = function(klass) {
  191. if(klass.wrapped) {
  192. copySuperclass(klass);
  193. }
  194. if(klass.wrapped) {
  195. dnu.installHandlers(klass);
  196. }
  197. };
  198. function copySuperclass(klass, superclass) {
  199. var inheritedMethods = Object.create(null);
  200. deinstallAllMethods(klass);
  201. for (superclass = superclass || klass.superclass;
  202. superclass && superclass !== nil;
  203. superclass = superclass.superclass) {
  204. for (var keys = Object.keys(superclass.methods), i = 0; i < keys.length; i++) {
  205. inheritMethodIfAbsent(superclass.methods[keys[i]]);
  206. }
  207. }
  208. manip.reinstallMethods(klass);
  209. function inheritMethodIfAbsent(method) {
  210. var selector = method.selector;
  211. //TODO: prepare klass methods into inheritedMethods to only test once
  212. if(klass.methods[selector] || inheritedMethods[selector]) {
  213. return;
  214. }
  215. manip.installMethod(method, klass);
  216. inheritedMethods[method.selector] = true;
  217. }
  218. }
  219. function deinstallAllMethods(klass) {
  220. var proto = klass.fn.prototype;
  221. for(var keys = Object.getOwnPropertyNames(proto), i=0; i<keys.length; i++) {
  222. var key = keys[i];
  223. if (dnu.isSelector(key)) {
  224. proto[key] = null;
  225. }
  226. }
  227. }
  228. }
  229. function ManipulationBrik(brikz, st) {
  230. this.installMethodIfAbsent = function (handler, klass) {
  231. if(!klass.fn.prototype[handler.jsSelector]) {
  232. installMethod(handler, klass);
  233. }
  234. };
  235. function installMethod (method, klass) {
  236. Object.defineProperty(klass.fn.prototype, method.jsSelector, {
  237. value: method.fn,
  238. enumerable: false, configurable: true, writable: true
  239. });
  240. }
  241. this.installMethod = installMethod;
  242. this.reinstallMethods = function (klass) {
  243. var methods = klass.methods;
  244. for(var keys = Object.keys(methods), i=0; i<keys.length; i++) {
  245. installMethod(methods[keys[i]], klass);
  246. }
  247. };
  248. }
  249. function ClassesBrik(brikz, st) {
  250. var org = brikz.ensure("organize");
  251. var root = brikz.ensure("root");
  252. var nil = root.nil;
  253. var rootAsClass = root.rootAsClass;
  254. var SmalltalkObject = root.Object;
  255. rootAsClass.klass = {fn: SmalltalkClass};
  256. function SmalltalkPackage() {}
  257. function SmalltalkBehavior() {}
  258. function SmalltalkClass() {}
  259. function SmalltalkMetaclass() {}
  260. inherits(SmalltalkPackage, SmalltalkObject);
  261. inherits(SmalltalkBehavior, SmalltalkObject);
  262. inherits(SmalltalkClass, SmalltalkBehavior);
  263. inherits(SmalltalkMetaclass, SmalltalkBehavior);
  264. SmalltalkMetaclass.prototype.meta = true;
  265. this.__init__ = function () {
  266. st.addPackage("Kernel-Classes");
  267. st.wrapClassName("Behavior", "Kernel-Classes", SmalltalkBehavior, st.Object, false);
  268. st.wrapClassName("Metaclass", "Kernel-Classes", SmalltalkMetaclass, st.Behavior, false);
  269. st.wrapClassName("Class", "Kernel-Classes", SmalltalkClass, st.Behavior, false);
  270. // Manually bootstrap the metaclass hierarchy
  271. st.ProtoObject.klass.superclass = rootAsClass.klass = st.Class;
  272. addSubclass(st.ProtoObject.klass);
  273. st.wrapClassName("Package", "Kernel-Infrastructure", SmalltalkPackage, st.Object, false);
  274. };
  275. /* Smalltalk classes */
  276. var classes = [];
  277. var wrappedClasses = [];
  278. /* We hold all Packages in a separate Object */
  279. st.packages = {};
  280. /* Smalltalk package creation. To add a Package, use smalltalk.addPackage() */
  281. function pkg(spec) {
  282. var that = new SmalltalkPackage();
  283. that.pkgName = spec.pkgName;
  284. org.setupPackageOrganization(that);
  285. that.properties = spec.properties || {};
  286. return that;
  287. }
  288. /* Smalltalk class creation. A class is an instance of an automatically
  289. created metaclass object. Newly created classes (not their metaclass)
  290. should be added to the smalltalk object, see smalltalk.addClass().
  291. Superclass linking is *not* handled here, see smalltalk.init() */
  292. function klass(spec) {
  293. spec = spec || {};
  294. var setSuperClass = spec.superclass;
  295. if(!spec.superclass) {
  296. spec.superclass = rootAsClass;
  297. }
  298. var meta = metaclass(spec);
  299. var that = meta.instanceClass;
  300. that.superclass = setSuperClass;
  301. that.fn = spec.fn || inherits(function () {}, spec.superclass.fn);
  302. that.subclasses = [];
  303. setupClass(that, spec);
  304. that.className = spec.className;
  305. that.wrapped = spec.wrapped || false;
  306. meta.className = spec.className + ' class';
  307. meta.superclass = spec.superclass.klass;
  308. return that;
  309. }
  310. function metaclass(spec) {
  311. spec = spec || {};
  312. var that = new SmalltalkMetaclass();
  313. that.fn = inherits(function () {}, spec.superclass.klass.fn);
  314. that.instanceClass = new that.fn();
  315. setupClass(that);
  316. return that;
  317. }
  318. SmalltalkBehavior.prototype.toString = function () {
  319. return 'Smalltalk ' + this.className;
  320. };
  321. function setupClass(klass, spec) {
  322. spec = spec || {};
  323. klass.iVarNames = spec.iVarNames || [];
  324. klass.pkg = spec.pkg;
  325. org.setupClassOrganization(klass);
  326. Object.defineProperty(klass, "methods", {
  327. value: Object.create(null),
  328. enumerable: false, configurable: true, writable: true
  329. });
  330. Object.defineProperty(klass.fn.prototype, "klass", {
  331. value: klass,
  332. enumerable: false, configurable: true, writable: true
  333. });
  334. }
  335. /* Add a package to the smalltalk.packages object, creating a new one if needed.
  336. If pkgName is null or empty we return nil, which is an allowed package for a class.
  337. If package already exists we still update the properties of it. */
  338. st.addPackage = function(pkgName, properties) {
  339. if(!pkgName) {return nil;}
  340. if(!(st.packages[pkgName])) {
  341. st.packages[pkgName] = pkg({
  342. pkgName: pkgName,
  343. properties: properties
  344. });
  345. } else {
  346. if(properties) {
  347. st.packages[pkgName].properties = properties;
  348. }
  349. }
  350. return st.packages[pkgName];
  351. };
  352. /* Add a class to the smalltalk object, creating a new one if needed.
  353. A Package is lazily created if it does not exist with given name. */
  354. st.addClass = function(className, superclass, iVarNames, pkgName) {
  355. if (superclass == nil) { superclass = null; }
  356. // While subclassing nil is allowed, it might be an error, so
  357. // warn about it.
  358. if (superclass === null) {
  359. console.warn('Compiling ' + className + ' as a subclass of `nil`. A dependency might be missing.');
  360. }
  361. rawAddClass(pkgName, className, superclass, iVarNames, false, null);
  362. };
  363. function rawAddClass(pkgName, className, superclass, iVarNames, wrapped, fn) {
  364. var pkg = st.packages[pkgName];
  365. if (!pkg) {
  366. throw new Error("Missing package "+pkgName);
  367. }
  368. if(st[className] && st[className].superclass == superclass) {
  369. // st[className].superclass = superclass;
  370. st[className].iVarNames = iVarNames || [];
  371. if (pkg) st[className].pkg = pkg;
  372. if (fn) {
  373. fn.prototype = st[className].fn.prototype;
  374. st[className].fn = fn;
  375. fn.prototype.constructor = fn;
  376. }
  377. } else {
  378. if(st[className]) {
  379. st.removeClass(st[className]);
  380. }
  381. st[className] = klass({
  382. className: className,
  383. superclass: superclass,
  384. pkg: pkg,
  385. iVarNames: iVarNames,
  386. fn: fn,
  387. wrapped: wrapped
  388. });
  389. addSubclass(st[className]);
  390. }
  391. classes.addElement(st[className]);
  392. org.addOrganizationElement(pkg, st[className]);
  393. }
  394. st.removeClass = function(klass) {
  395. org.removeOrganizationElement(klass.pkg, klass);
  396. classes.removeElement(klass);
  397. removeSubclass(klass);
  398. delete st[klass.className];
  399. };
  400. function addSubclass(klass) {
  401. if(klass.superclass) {
  402. klass.superclass.subclasses.addElement(klass);
  403. }
  404. }
  405. function removeSubclass(klass) {
  406. if(klass.superclass) {
  407. klass.superclass.subclasses.removeElement(klass);
  408. }
  409. }
  410. /* Create a new class wrapping a JavaScript constructor, and add it to the
  411. global smalltalk object. Package is lazily created if it does not exist with given name. */
  412. st.wrapClassName = function(className, pkgName, fn, superclass, wrapped) {
  413. wrapped = wrapped !== false;
  414. rawAddClass(pkgName, className, superclass, st[className] && st[className].iVarNames, wrapped, fn);
  415. if(wrapped) {
  416. wrappedClasses.addElement(st[className]);
  417. }
  418. };
  419. /* Manually set the constructor of an existing Smalltalk klass, making it a wrapped class. */
  420. st.setClassConstructor = function(klass, constructor) {
  421. wrappedClasses.addElement(klass);
  422. klass.wrapped = true;
  423. klass.fn = constructor;
  424. // The fn property changed. We need to add back the klass property to the prototype
  425. Object.defineProperty(klass.fn.prototype, "klass", {
  426. value: klass,
  427. enumerable: false, configurable: true, writable: true
  428. });
  429. st.initClass(klass);
  430. };
  431. /* Create an alias for an existing class */
  432. st.alias = function(klass, alias) {
  433. st[alias] = klass;
  434. };
  435. /* Answer all registered Smalltalk classes */
  436. //TODO: remove the function and make smalltalk.classes an array
  437. st.classes = function() {
  438. return classes;
  439. };
  440. st.wrappedClasses = function() {
  441. return wrappedClasses;
  442. };
  443. // Still used, but could go away now that subclasses are stored
  444. // into classes directly.
  445. st.allSubclasses = function(klass) {
  446. return klass._allSubclasses();
  447. };
  448. }
  449. function MethodsBrik(brikz, st) {
  450. var manip = brikz.ensure("manipulation");
  451. var org = brikz.ensure("organize");
  452. var stInit = brikz.ensure("stInit");
  453. var dnu = brikz.ensure("dnu");
  454. var SmalltalkObject = brikz.ensure("root").Object;
  455. brikz.ensure("selectorConversion");
  456. brikz.ensure("classes");
  457. brikz.ensure("classInit");
  458. function SmalltalkMethod() {}
  459. inherits(SmalltalkMethod, SmalltalkObject);
  460. this.__init__ = function () {
  461. st.addPackage("Kernel-Methods");
  462. st.wrapClassName("CompiledMethod", "Kernel-Methods", SmalltalkMethod, st.Object, false);
  463. };
  464. /* Smalltalk method object. To add a method to a class,
  465. use smalltalk.addMethod() */
  466. st.method = function(spec) {
  467. var that = new SmalltalkMethod();
  468. that.selector = spec.selector;
  469. that.jsSelector = spec.jsSelector;
  470. that.args = spec.args || {};
  471. // spec.category is kept for compatibility
  472. that.protocol = spec.protocol || spec.category;
  473. that.source = spec.source;
  474. that.messageSends = spec.messageSends || [];
  475. that.referencedClasses = spec.referencedClasses || [];
  476. that.fn = spec.fn;
  477. return that;
  478. };
  479. function installNewDnuHandler(newHandler) {
  480. var wrappedClasses = st.wrappedClasses();
  481. for(var i = 0; i < wrappedClasses.length; i++) {
  482. manip.installMethodIfAbsent(newHandler, wrappedClasses[i]);
  483. }
  484. }
  485. /* Add/remove a method to/from a class */
  486. st.addMethod = function (method, klass) {
  487. if (!(method.jsSelector)) {
  488. method.jsSelector = st.selector(method.selector);
  489. }
  490. manip.installMethod(method, klass);
  491. klass.methods[method.selector] = method;
  492. method.methodClass = klass;
  493. // During the bootstrap, #addCompiledMethod is not used.
  494. // Therefore we populate the organizer here too
  495. org.addOrganizationElement(klass, method.protocol);
  496. propagateMethodChange(klass);
  497. for(var i=0; i<method.messageSends.length; i++) {
  498. var dnuHandler = dnu.get(method.messageSends[i]);
  499. if(stInit.initialized()) {
  500. installNewDnuHandler(dnuHandler);
  501. }
  502. }
  503. };
  504. function propagateMethodChange(klass) {
  505. // If already initialized (else it will be done later anyway),
  506. // re-initialize all subclasses to ensure the method change
  507. // propagation (for wrapped classes, not using the prototype
  508. // chain).
  509. //TODO: optimize, only one method need to be updated, not all of them
  510. if (stInit.initialized()) {
  511. st.allSubclasses(klass).forEach(function (subclass) {
  512. st.initClass(subclass);
  513. });
  514. }
  515. }
  516. st.removeMethod = function(method, klass) {
  517. if (klass !== method.methodClass) {
  518. throw new Error(
  519. "Refusing to remove method "
  520. + method.methodClass.className+">>"+method.selector
  521. + " from different class "
  522. + klass.className);
  523. }
  524. delete klass.fn.prototype[st.selector(method.selector)];
  525. delete klass.methods[method.selector];
  526. st.initClass(klass);
  527. propagateMethodChange(klass);
  528. // Do *not* delete protocols from here.
  529. // This is handled by #removeCompiledMethod
  530. };
  531. /* Answer all method selectors based on dnu handlers */
  532. st.allSelectors = function() {
  533. return dnu.selectors;
  534. };
  535. }
  536. function AugmentsBrik(brikz, st) {
  537. /* Make sure that console is defined */
  538. if(typeof console === "undefined") {
  539. this.console = {
  540. log: function() {},
  541. warn: function() {},
  542. info: function() {},
  543. debug: function() {},
  544. error: function() {}
  545. };
  546. }
  547. /* Array extensions */
  548. Array.prototype.addElement = function(el) {
  549. if(typeof el === 'undefined') { return; }
  550. if(this.indexOf(el) == -1) {
  551. this.push(el);
  552. }
  553. };
  554. Array.prototype.removeElement = function(el) {
  555. var i = this.indexOf(el);
  556. if (i !== -1) { this.splice(i, 1); }
  557. };
  558. }
  559. function SmalltalkInitBrik(brikz, st) {
  560. brikz.ensure("classInit");
  561. brikz.ensure("classes");
  562. var nil = brikz.ensure("root").nil;
  563. var initialized = false;
  564. /* Smalltalk initialization. Called on page load */
  565. st.initialize = function() {
  566. if(initialized) { return; }
  567. st.classes().forEach(function(klass) {
  568. st.init(klass);
  569. });
  570. runnable();
  571. st.classes().forEach(function(klass) {
  572. klass._initialize();
  573. });
  574. initialized = true;
  575. };
  576. this.initialized = function () {
  577. return initialized;
  578. };
  579. this.__init__ = function () {
  580. st.addPackage("Kernel-Methods");
  581. st.wrapClassName("Number", "Kernel-Objects", Number, st.Object);
  582. st.wrapClassName("BlockClosure", "Kernel-Methods", Function, st.Object);
  583. st.wrapClassName("Boolean", "Kernel-Objects", Boolean, st.Object);
  584. st.wrapClassName("Date", "Kernel-Objects", Date, st.Object);
  585. st.addPackage("Kernel-Collections");
  586. st.addClass("Collection", st.Object, null, "Kernel-Collections");
  587. st.addClass("IndexableCollection", st.Collection, null, "Kernel-Collections");
  588. st.addClass("SequenceableCollection", st.IndexableCollection, null, "Kernel-Collections");
  589. st.addClass("CharacterArray", st.SequenceableCollection, null, "Kernel-Collections");
  590. st.wrapClassName("String", "Kernel-Collections", String, st.CharacterArray);
  591. st.wrapClassName("Array", "Kernel-Collections", Array, st.SequenceableCollection);
  592. st.wrapClassName("RegularExpression", "Kernel-Collections", RegExp, st.Object);
  593. st.addPackage("Kernel-Exceptions");
  594. st.wrapClassName("Error", "Kernel-Exceptions", Error, st.Object);
  595. /* Alias definitions */
  596. st.alias(st.Array, "OrderedCollection");
  597. st.alias(st.Date, "Time");
  598. };
  599. }
  600. function PrimitivesBrik(brikz, st) {
  601. /* Unique ID number generator */
  602. var oid = 0;
  603. st.nextId = function() {
  604. oid += 1;
  605. return oid;
  606. };
  607. /* Converts a JavaScript object to valid Smalltalk Object */
  608. st.readJSObject = function(js) {
  609. var object = js;
  610. var readObject = (js.constructor === Object);
  611. var readArray = (js.constructor === Array);
  612. if(readObject) {
  613. object = st.Dictionary._new();
  614. }
  615. for(var i in js) {
  616. if(readObject) {
  617. object._at_put_(i, st.readJSObject(js[i]));
  618. }
  619. if(readArray) {
  620. object[i] = st.readJSObject(js[i]);
  621. }
  622. }
  623. return object;
  624. };
  625. /* Boolean assertion */
  626. st.assert = function(shouldBeBoolean) {
  627. if (undefined !== shouldBeBoolean && shouldBeBoolean.klass === st.Boolean) {
  628. return shouldBeBoolean == true;
  629. } else {
  630. st.NonBooleanReceiver._new()._object_(shouldBeBoolean)._signal();
  631. }
  632. };
  633. /* List of all reserved words in JavaScript. They may not be used as variables
  634. in Smalltalk. */
  635. // list of reserved JavaScript keywords as of
  636. // http://es5.github.com/#x7.6.1.1
  637. // and
  638. // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.6.1
  639. st.reservedWords = ['break', 'case', 'catch', 'continue', 'debugger',
  640. 'default', 'delete', 'do', 'else', 'finally', 'for', 'function',
  641. 'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', 'throw',
  642. 'try', 'typeof', 'var', 'void', 'while', 'with',
  643. // ES5: future use: http://es5.github.com/#x7.6.1.2
  644. 'class', 'const', 'enum', 'export', 'extends', 'import', 'super',
  645. // ES5: future use in strict mode
  646. 'implements', 'interface', 'let', 'package', 'private', 'protected',
  647. 'public', 'static', 'yield'];
  648. st.globalJsVariables = ['jQuery', 'window', 'document', 'process', 'global'];
  649. }
  650. function RuntimeBrik(brikz, st) {
  651. brikz.ensure("selectorConversion");
  652. var root = brikz.ensure("root");
  653. var nil = root.nil;
  654. var SmalltalkObject = root.Object;
  655. function SmalltalkMethodContext(home, setup) {
  656. this.sendIdx = {};
  657. this.homeContext = home;
  658. this.setup = setup || function() {};
  659. }
  660. inherits(SmalltalkMethodContext, SmalltalkObject);
  661. this.__init__ = function () {
  662. st.addPackage("Kernel-Methods");
  663. st.wrapClassName("MethodContext", "Kernel-Methods", SmalltalkMethodContext, st.Object, false);
  664. // Fallbacks
  665. SmalltalkMethodContext.prototype.locals = {};
  666. SmalltalkMethodContext.prototype.receiver = null;
  667. SmalltalkMethodContext.prototype.selector = null;
  668. SmalltalkMethodContext.prototype.lookupClass = null;
  669. SmalltalkMethodContext.prototype.fill = function(receiver, selector, locals, lookupClass) {
  670. this.receiver = receiver;
  671. this.selector = selector;
  672. this.locals = locals || {};
  673. this.lookupClass = lookupClass;
  674. if(this.homeContext) {
  675. this.homeContext.evaluatedSelector = selector;
  676. }
  677. };
  678. SmalltalkMethodContext.prototype.fillBlock = function(locals, ctx, index) {
  679. this.locals = locals || {};
  680. this.outerContext = ctx;
  681. this.index = index || 0;
  682. };
  683. SmalltalkMethodContext.prototype.init = function() {
  684. var home = this.homeContext;
  685. if(home) {
  686. home.init();
  687. }
  688. this.setup(this);
  689. };
  690. SmalltalkMethodContext.prototype.method = function() {
  691. var method;
  692. var lookup = this.lookupClass || this.receiver.klass;
  693. while(!method && lookup) {
  694. method = lookup.methods[st.convertSelector(this.selector)];
  695. lookup = lookup.superclass;
  696. }
  697. return method;
  698. };
  699. };
  700. /* This is the current call context object. While it is publicly available,
  701. Use smalltalk.getThisContext() instead which will answer a safe copy of
  702. the current context */
  703. st.thisContext = undefined;
  704. st.withContext = function(worker, setup) {
  705. if(st.thisContext) {
  706. return inContext(worker, setup);
  707. } else {
  708. try {
  709. return inContext(worker, setup);
  710. } catch(error) {
  711. handleError(error);
  712. st.thisContext = null;
  713. }
  714. }
  715. };
  716. function inContext(worker, setup) {
  717. var context = pushContext(setup);
  718. var result = worker(context);
  719. popContext(context);
  720. return result;
  721. }
  722. /* Wrap a JavaScript exception in a Smalltalk Exception.
  723. In case of a RangeError, stub the stack after 100 contexts to
  724. avoid another RangeError later when the stack is manipulated. */
  725. function wrappedError(error) {
  726. var errorWrapper = st.JavaScriptException._on_(error);
  727. // Add the error to the context, so it is visible in the stack
  728. try { errorWrapper._signal(); } catch (ex) {}
  729. var context = st.getThisContext();
  730. if(isRangeError(error)) {
  731. stubContextStack(context);
  732. }
  733. errorWrapper._context_(context);
  734. return errorWrapper;
  735. }
  736. /* Stub the context stack after 100 contexts */
  737. function stubContextStack(context) {
  738. var currentContext = context;
  739. var contexts = 0;
  740. while(contexts < 100) {
  741. if(currentContext) {
  742. currentContext = currentContext.homeContext;
  743. }
  744. contexts++;
  745. }
  746. if(currentContext) {
  747. currentContext.homeContext = undefined;
  748. }
  749. }
  750. function isRangeError(error) {
  751. return error instanceof RangeError;
  752. }
  753. /* Handles Smalltalk errors. Triggers the registered ErrorHandler
  754. (See the Smalltalk class ErrorHandler and its subclasses */
  755. function handleError(error) {
  756. if (!error.smalltalkError) {
  757. error = wrappedError(error);
  758. }
  759. st.ErrorHandler._current()._handleError_(error);
  760. // Throw the exception anyway, as we want to stop
  761. // the execution to avoid infinite loops
  762. // Update: do not throw the exception. It's really annoying.
  763. // throw error;
  764. }
  765. /* Handle thisContext pseudo variable */
  766. st.getThisContext = function() {
  767. if(st.thisContext) {
  768. st.thisContext.init();
  769. return st.thisContext;
  770. } else {
  771. return nil;
  772. }
  773. };
  774. function pushContext(setup) {
  775. return st.thisContext = new SmalltalkMethodContext(st.thisContext, setup);
  776. }
  777. function popContext(context) {
  778. st.thisContext = context.homeContext;
  779. }
  780. }
  781. function MessageSendBrik(brikz, st) {
  782. brikz.ensure("selectorConversion");
  783. var nil = brikz.ensure("root").nil;
  784. /* Handles unhandled errors during message sends */
  785. // simply send the message and handle #dnu:
  786. st.send = function(receiver, selector, args, klass) {
  787. var method;
  788. if(receiver === null) {
  789. receiver = nil;
  790. }
  791. method = klass ? klass.fn.prototype[selector] : receiver.klass && receiver[selector];
  792. if(method) {
  793. return method.apply(receiver, args);
  794. } else {
  795. return messageNotUnderstood(receiver, selector, args);
  796. }
  797. };
  798. /* Handles #dnu: *and* JavaScript method calls.
  799. if the receiver has no klass, we consider it a JS object (outside of the
  800. Amber system). Else assume that the receiver understands #doesNotUnderstand: */
  801. function messageNotUnderstood(receiver, selector, args) {
  802. /* Handles JS method calls. */
  803. if(receiver.klass === undefined || receiver.allowJavaScriptCalls) {
  804. return callJavaScriptMethod(receiver, selector, args);
  805. }
  806. /* Handles not understood messages. Also see the Amber counter-part
  807. Object>>doesNotUnderstand: */
  808. return receiver._doesNotUnderstand_(
  809. st.Message._new()
  810. ._selector_(st.convertSelector(selector))
  811. ._arguments_(args)
  812. );
  813. }
  814. /* Call a method of a JS object, or answer a property if it exists.
  815. Else try wrapping a JSObjectProxy around the receiver.
  816. If the object property is a function, then call it, except if it starts with
  817. an uppercase character (we probably want to answer the function itself in this
  818. case and send it #new from Amber).
  819. Converts keyword-based selectors by using the first
  820. keyword only, but keeping all message arguments.
  821. Example:
  822. "self do: aBlock with: anObject" -> "self.do(aBlock, anObject)" */
  823. function callJavaScriptMethod(receiver, selector, args) {
  824. var jsSelector = selector._asJavaScriptSelector();
  825. var jsProperty = receiver[jsSelector];
  826. if(typeof jsProperty === "function" && !/^[A-Z]/.test(jsSelector)) {
  827. return jsProperty.apply(receiver, args);
  828. } else if(jsProperty !== undefined) {
  829. if(args[0]) {
  830. receiver[jsSelector] = args[0];
  831. return nil;
  832. } else {
  833. return jsProperty;
  834. }
  835. }
  836. return st.send(st.JSObjectProxy._on_(receiver), selector, args);
  837. }
  838. if(typeof jQuery !== "undefined") {
  839. jQuery.allowJavaScriptCalls = true;
  840. }
  841. this.messageNotUnderstood = messageNotUnderstood;
  842. }
  843. function SelectorConversionBrik(brikz, st) {
  844. /* Convert a Smalltalk selector into a JS selector */
  845. st.selector = function(string) {
  846. var selector = '_' + string;
  847. selector = selector.replace(/:/g, '_');
  848. selector = selector.replace(/[\&]/g, '_and');
  849. selector = selector.replace(/[\|]/g, '_or');
  850. selector = selector.replace(/[+]/g, '_plus');
  851. selector = selector.replace(/-/g, '_minus');
  852. selector = selector.replace(/[*]/g ,'_star');
  853. selector = selector.replace(/[\/]/g ,'_slash');
  854. selector = selector.replace(/[\\]/g ,'_backslash');
  855. selector = selector.replace(/[\~]/g ,'_tild');
  856. selector = selector.replace(/>/g ,'_gt');
  857. selector = selector.replace(/</g ,'_lt');
  858. selector = selector.replace(/=/g ,'_eq');
  859. selector = selector.replace(/,/g ,'_comma');
  860. selector = selector.replace(/[@]/g ,'_at');
  861. return selector;
  862. };
  863. /* Convert a string to a valid smalltalk selector.
  864. if you modify the following functions, also change String>>asSelector
  865. accordingly */
  866. st.convertSelector = function(selector) {
  867. if(selector.match(/__/)) {
  868. return convertBinarySelector(selector);
  869. } else {
  870. return convertKeywordSelector(selector);
  871. }
  872. };
  873. function convertKeywordSelector(selector) {
  874. return selector.replace(/^_/, '').replace(/_/g, ':');
  875. }
  876. function convertBinarySelector(selector) {
  877. return selector
  878. .replace(/^_/, '')
  879. .replace(/_and/g, '&')
  880. .replace(/_or/g, '|')
  881. .replace(/_plus/g, '+')
  882. .replace(/_minus/g, '-')
  883. .replace(/_star/g, '*')
  884. .replace(/_slash/g, '/')
  885. .replace(/_backslash/g, '\\')
  886. .replace(/_tild/g, '~')
  887. .replace(/_gt/g, '>')
  888. .replace(/_lt/g, '<')
  889. .replace(/_eq/g, '=')
  890. .replace(/_comma/g, ',')
  891. .replace(/_at/g, '@');
  892. }
  893. }
  894. /* Adds AMD and requirejs related methods to the smalltalk object */
  895. function AMDBrik(brikz, st) {
  896. this.__init__ = function () {
  897. st.amdRequire = st.amdRequire || null;
  898. st.defaultTransportType = st.defaultTransportType || "amd";
  899. st.defaultAmdNamespace = st.defaultAmdNamespace || "amber_core";
  900. };
  901. }
  902. /* Making smalltalk that can load */
  903. brikz.root = RootBrik;
  904. brikz.dnu = DNUBrik;
  905. brikz.organize = OrganizeBrik;
  906. brikz.selectorConversion = SelectorConversionBrik;
  907. brikz.classInit = ClassInitBrik;
  908. brikz.manipulation = ManipulationBrik;
  909. brikz.classes = ClassesBrik;
  910. brikz.methods = MethodsBrik;
  911. brikz.stInit = SmalltalkInitBrik;
  912. brikz.augments = AugmentsBrik;
  913. brikz.amdBrik = AMDBrik;
  914. brikz.rebuild();
  915. /* Making smalltalk that can run */
  916. function runnable () {
  917. brikz.messageSend = MessageSendBrik;
  918. brikz.runtime = RuntimeBrik;
  919. brikz.primitives = PrimitivesBrik;
  920. brikz.rebuild();
  921. };
  922. return { smalltalk: api, nil: brikz.root.nil };
  923. });