2
0

boot.js 30 KB

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