2
0

boot.js 33 KB

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