boot.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. /* Manually set the constructor of an existing Smalltalk klass, making it a wrapped class. */
  403. st.setClassConstructor = function(klass, constructor) {
  404. wrappedClasses.addElement(klass);
  405. klass.wrapped = true;
  406. klass.fn = constructor;
  407. // The fn property changed. We need to add back the klass property to the prototype
  408. Object.defineProperty(klass.fn.prototype, "klass", {
  409. value: klass,
  410. enumerable: false, configurable: true, writable: true
  411. });
  412. st.initClass(klass);
  413. };
  414. /* Create an alias for an existing class */
  415. st.alias = function(klass, alias) {
  416. st[alias] = klass;
  417. };
  418. /* Answer all registered Smalltalk classes */
  419. //TODO: remove the function and make smalltalk.classes an array
  420. st.classes = function() {
  421. return classes;
  422. };
  423. st.wrappedClasses = function() {
  424. return wrappedClasses;
  425. };
  426. // Still used, but could go away now that subclasses are stored
  427. // into classes directly.
  428. st.allSubclasses = function(klass) {
  429. return klass._allSubclasses();
  430. };
  431. }
  432. function MethodsBrik(brikz, st) {
  433. var manip = brikz.ensure("manipulation");
  434. var org = brikz.ensure("organize");
  435. var stInit = brikz.ensure("stInit");
  436. var dnu = brikz.ensure("dnu");
  437. brikz.ensure("selectorConversion");
  438. brikz.ensure("classes");
  439. brikz.ensure("classInit");
  440. function SmalltalkMethod() {}
  441. inherits(SmalltalkMethod, SmalltalkObject);
  442. this.__init__ = function () {
  443. st.addPackage("Kernel-Methods");
  444. st.wrapClassName("CompiledMethod", "Kernel-Methods", SmalltalkMethod, st.Object, false);
  445. };
  446. /* Smalltalk method object. To add a method to a class,
  447. use smalltalk.addMethod() */
  448. st.method = function(spec) {
  449. var that = new SmalltalkMethod();
  450. that.selector = spec.selector;
  451. that.jsSelector = spec.jsSelector;
  452. that.args = spec.args || {};
  453. that.category = spec.category;
  454. that.source = spec.source;
  455. that.messageSends = spec.messageSends || [];
  456. that.referencedClasses = spec.referencedClasses || [];
  457. that.fn = spec.fn;
  458. return that;
  459. };
  460. function installNewDnuHandler(newHandler) {
  461. manip.installMethodIfAbsent(newHandler, st.Object);
  462. var wrappedClasses = st.wrappedClasses();
  463. for(var i = 0; i < wrappedClasses.length; i++) {
  464. manip.installMethodIfAbsent(newHandler, wrappedClasses[i]);
  465. }
  466. }
  467. /* Add/remove a method to/from a class */
  468. st.addMethod = function (method, klass) {
  469. if (!(method.jsSelector)) {
  470. method.jsSelector = st.selector(method.selector);
  471. }
  472. manip.installMethod(method, klass);
  473. klass.methods[method.selector] = method;
  474. method.methodClass = klass;
  475. // During the bootstrap, #addCompiledMethod is not used.
  476. // Therefore we populate the organizer here too
  477. org.addOrganizationElement(klass, method.category);
  478. propagateMethodChange(klass);
  479. for(var i=0; i<method.messageSends.length; i++) {
  480. var dnuHandler = dnu.get(method.messageSends[i]);
  481. if(stInit.initialized()) {
  482. installNewDnuHandler(dnuHandler);
  483. }
  484. }
  485. };
  486. function propagateMethodChange(klass) {
  487. // If already initialized (else it will be done later anyway),
  488. // re-initialize all subclasses to ensure the method change
  489. // propagation (for wrapped classes, not using the prototype
  490. // chain).
  491. //TODO: optimize, only one method need to be updated, not all of them
  492. if (stInit.initialized()) {
  493. st.allSubclasses(klass).forEach(function (subclass) {
  494. st.initClass(subclass);
  495. });
  496. }
  497. }
  498. st.removeMethod = function(method, klass) {
  499. if (klass !== method.methodClass) {
  500. throw new Error(
  501. "Refusing to remove method "
  502. + method.methodClass.className+">>"+method.selector
  503. + " from different class "
  504. + klass.className);
  505. }
  506. delete klass.fn.prototype[st.selector(method.selector)];
  507. delete klass.methods[method.selector];
  508. st.initClass(klass);
  509. propagateMethodChange(klass);
  510. // Do *not* delete protocols from here.
  511. // This is handled by #removeCompiledMethod
  512. };
  513. /* Answer all method selectors based on dnu handlers */
  514. st.allSelectors = function() {
  515. return dnu.selectors;
  516. };
  517. }
  518. function AugmentsBrik(brikz, st) {
  519. /* Make sure that console is defined */
  520. if(typeof console === "undefined") {
  521. this.console = {
  522. log: function() {},
  523. warn: function() {},
  524. info: function() {},
  525. debug: function() {},
  526. error: function() {}
  527. };
  528. }
  529. /* Array extensions */
  530. Array.prototype.addElement = function(el) {
  531. if(typeof el === 'undefined') { return; }
  532. if(this.indexOf(el) == -1) {
  533. this.push(el);
  534. }
  535. };
  536. Array.prototype.removeElement = function(el) {
  537. var i = this.indexOf(el);
  538. if (i !== -1) { this.splice(i, 1); }
  539. };
  540. }
  541. function SmalltalkInitBrik(brikz, st) {
  542. brikz.ensure("classInit");
  543. brikz.ensure("classes");
  544. var nil = brikz.ensure("root").nil;
  545. var initialized = false;
  546. /* Smalltalk initialization. Called on page load */
  547. st.initialize = function() {
  548. if(initialized) { return; }
  549. st.classes().forEach(function(klass) {
  550. st.init(klass);
  551. });
  552. runnable();
  553. st.classes().forEach(function(klass) {
  554. klass._initialize();
  555. });
  556. initialized = true;
  557. };
  558. this.initialized = function () {
  559. return initialized;
  560. };
  561. this.__init__ = function () {
  562. st.addPackage("Kernel-Methods");
  563. st.wrapClassName("Number", "Kernel-Objects", Number, st.Object);
  564. st.wrapClassName("BlockClosure", "Kernel-Methods", Function, st.Object);
  565. st.wrapClassName("Boolean", "Kernel-Objects", Boolean, st.Object);
  566. st.wrapClassName("Date", "Kernel-Objects", Date, st.Object);
  567. st.addPackage("Kernel-Collections");
  568. st.addClass("Collection", st.Object, null, "Kernel-Collections");
  569. st.addClass("IndexableCollection", st.Collection, null, "Kernel-Collections");
  570. st.addClass("SequenceableCollection", st.IndexableCollection, null, "Kernel-Collections");
  571. st.addClass("CharacterArray", st.SequenceableCollection, null, "Kernel-Collections");
  572. st.wrapClassName("String", "Kernel-Collections", String, st.CharacterArray);
  573. st.wrapClassName("Array", "Kernel-Collections", Array, st.SequenceableCollection);
  574. st.wrapClassName("RegularExpression", "Kernel-Collections", RegExp, st.Object);
  575. st.addPackage("Kernel-Exceptions");
  576. st.wrapClassName("Error", "Kernel-Exceptions", Error, st.Object);
  577. /* Alias definitions */
  578. st.alias(st.Array, "OrderedCollection");
  579. st.alias(st.Date, "Time");
  580. };
  581. }
  582. function PrimitivesBrik(brikz, st) {
  583. /* Unique ID number generator */
  584. var oid = 0;
  585. st.nextId = function() {
  586. oid += 1;
  587. return oid;
  588. };
  589. /* Converts a JavaScript object to valid Smalltalk Object */
  590. st.readJSObject = function(js) {
  591. var object = js;
  592. var readObject = (js.constructor === Object);
  593. var readArray = (js.constructor === Array);
  594. if(readObject) {
  595. object = st.Dictionary._new();
  596. }
  597. for(var i in js) {
  598. if(readObject) {
  599. object._at_put_(i, st.readJSObject(js[i]));
  600. }
  601. if(readArray) {
  602. object[i] = st.readJSObject(js[i]);
  603. }
  604. }
  605. return object;
  606. };
  607. /* Boolean assertion */
  608. st.assert = function(shouldBeBoolean) {
  609. if (undefined !== shouldBeBoolean && shouldBeBoolean.klass === st.Boolean) {
  610. return shouldBeBoolean == true;
  611. } else {
  612. st.NonBooleanReceiver._new()._object_(shouldBeBoolean)._signal();
  613. }
  614. };
  615. /* List of all reserved words in JavaScript. They may not be used as variables
  616. in Smalltalk. */
  617. // list of reserved JavaScript keywords as of
  618. // http://es5.github.com/#x7.6.1.1
  619. // and
  620. // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.6.1
  621. st.reservedWords = ['break', 'case', 'catch', 'continue', 'debugger',
  622. 'default', 'delete', 'do', 'else', 'finally', 'for', 'function',
  623. 'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', 'throw',
  624. 'try', 'typeof', 'var', 'void', 'while', 'with',
  625. // ES5: future use: http://es5.github.com/#x7.6.1.2
  626. 'class', 'const', 'enum', 'export', 'extends', 'import', 'super',
  627. // ES5: future use in strict mode
  628. 'implements', 'interface', 'let', 'package', 'private', 'protected',
  629. 'public', 'static', 'yield'];
  630. st.globalJsVariables = ['jQuery', 'window', 'document', 'process', 'global'];
  631. }
  632. function RuntimeBrik(brikz, st) {
  633. brikz.ensure("selectorConversion");
  634. var nil = brikz.ensure("root").nil;
  635. function SmalltalkMethodContext(home, setup) {
  636. this.homeContext = home;
  637. this.setup = setup || function() {};
  638. this.pc = 0;
  639. }
  640. inherits(SmalltalkMethodContext, SmalltalkObject);
  641. this.__init__ = function () {
  642. st.addPackage("Kernel-Methods");
  643. st.wrapClassName("MethodContext", "Kernel-Methods", SmalltalkMethodContext, st.Object, false);
  644. // Fallbacks
  645. SmalltalkMethodContext.prototype.locals = {};
  646. SmalltalkMethodContext.prototype.receiver = null;
  647. SmalltalkMethodContext.prototype.selector = null;
  648. SmalltalkMethodContext.prototype.lookupClass = null;
  649. SmalltalkMethodContext.prototype.fill = function(receiver, selector, locals, lookupClass) {
  650. this.receiver = receiver;
  651. this.selector = selector;
  652. this.locals = locals || {};
  653. this.lookupClass = lookupClass;
  654. };
  655. SmalltalkMethodContext.prototype.fillBlock = function(locals, ctx, index) {
  656. this.locals = locals || {};
  657. this.outerContext = ctx;
  658. this.index = index || 0;
  659. };
  660. SmalltalkMethodContext.prototype.init = function() {
  661. var home = this.homeContext;
  662. if(home) {
  663. home.init();
  664. }
  665. this.setup(this);
  666. };
  667. SmalltalkMethodContext.prototype.method = function() {
  668. var method;
  669. var lookup = this.lookupClass || this.receiver.klass;
  670. while(!method && lookup) {
  671. method = lookup.methods[st.convertSelector(this.selector)];
  672. lookup = lookup.superclass;
  673. }
  674. return method;
  675. };
  676. };
  677. /* This is the current call context object. While it is publicly available,
  678. Use smalltalk.getThisContext() instead which will answer a safe copy of
  679. the current context */
  680. st.thisContext = undefined;
  681. st.withContext = function(worker, setup) {
  682. if(st.thisContext) {
  683. st.thisContext.pc++;
  684. return inContext(worker, setup);
  685. } else {
  686. try {
  687. return inContext(worker, setup);
  688. } catch(error) {
  689. handleError(error);
  690. st.thisContext = null;
  691. }
  692. }
  693. };
  694. function inContext(worker, setup) {
  695. var context = pushContext(setup);
  696. var result = worker(context);
  697. popContext(context);
  698. return result;
  699. }
  700. function wrappedError(error) {
  701. var errorWrapper = st.JavaScriptException._on_(error);
  702. try { errorWrapper._signal(); } catch (ex) {}
  703. errorWrapper._context_(st.getThisContext());
  704. return errorWrapper;
  705. }
  706. /* Handles Smalltalk errors. Triggers the registered ErrorHandler
  707. (See the Smalltalk class ErrorHandler and its subclasses */
  708. function handleError(error) {
  709. if (!error.smalltalkError) {
  710. error = wrappedError(error);
  711. }
  712. st.ErrorHandler._current()._handleError_(error);
  713. // Throw the exception anyway, as we want to stop
  714. // the execution to avoid infinite loops
  715. // Update: do not throw the exception. It's really annoying.
  716. // throw error;
  717. }
  718. /* Handle thisContext pseudo variable */
  719. st.getThisContext = function() {
  720. if(st.thisContext) {
  721. st.thisContext.init();
  722. return st.thisContext;
  723. } else {
  724. return nil;
  725. }
  726. };
  727. function pushContext(setup) {
  728. return st.thisContext = new SmalltalkMethodContext(st.thisContext, setup);
  729. }
  730. function popContext(context) {
  731. st.thisContext = context.homeContext;
  732. }
  733. }
  734. function MessageSendBrik(brikz, st) {
  735. brikz.ensure("selectorConversion");
  736. var nil = brikz.ensure("root").nil;
  737. /* Handles unhandled errors during message sends */
  738. // simply send the message and handle #dnu:
  739. st.send = function(receiver, selector, args, klass) {
  740. var method;
  741. if(receiver === null) {
  742. receiver = nil;
  743. }
  744. method = klass ? klass.fn.prototype[selector] : receiver.klass && receiver[selector];
  745. if(method) {
  746. return method.apply(receiver, args);
  747. } else {
  748. return messageNotUnderstood(receiver, selector, args);
  749. }
  750. };
  751. /* Handles #dnu: *and* JavaScript method calls.
  752. if the receiver has no klass, we consider it a JS object (outside of the
  753. Amber system). Else assume that the receiver understands #doesNotUnderstand: */
  754. function messageNotUnderstood(receiver, selector, args) {
  755. /* Handles JS method calls. */
  756. if(receiver.klass === undefined || receiver.allowJavaScriptCalls) {
  757. return callJavaScriptMethod(receiver, selector, args);
  758. }
  759. /* Handles not understood messages. Also see the Amber counter-part
  760. Object>>doesNotUnderstand: */
  761. return receiver._doesNotUnderstand_(
  762. st.Message._new()
  763. ._selector_(st.convertSelector(selector))
  764. ._arguments_(args)
  765. );
  766. }
  767. /* Call a method of a JS object, or answer a property if it exists.
  768. Else try wrapping a JSObjectProxy around the receiver.
  769. If the object property is a function, then call it, except if it starts with
  770. an uppercase character (we probably want to answer the function itself in this
  771. case and send it #new from Amber).
  772. Converts keyword-based selectors by using the first
  773. keyword only, but keeping all message arguments.
  774. Example:
  775. "self do: aBlock with: anObject" -> "self.do(aBlock, anObject)" */
  776. function callJavaScriptMethod(receiver, selector, args) {
  777. var jsSelector = selector._asJavaScriptSelector();
  778. var jsProperty = receiver[jsSelector];
  779. if(typeof jsProperty === "function" && !/^[A-Z]/.test(jsSelector)) {
  780. return jsProperty.apply(receiver, args);
  781. } else if(jsProperty !== undefined) {
  782. if(args[0]) {
  783. receiver[jsSelector] = args[0];
  784. return nil;
  785. } else {
  786. return jsProperty;
  787. }
  788. }
  789. return st.send(st.JSObjectProxy._on_(receiver), selector, args);
  790. }
  791. if(typeof jQuery !== "undefined") {
  792. jQuery.allowJavaScriptCalls = true;
  793. }
  794. this.messageNotUnderstood = messageNotUnderstood;
  795. }
  796. function SelectorConversionBrik(brikz, st) {
  797. /* Convert a Smalltalk selector into a JS selector */
  798. st.selector = function(string) {
  799. var selector = '_' + string;
  800. selector = selector.replace(/:/g, '_');
  801. selector = selector.replace(/[\&]/g, '_and');
  802. selector = selector.replace(/[\|]/g, '_or');
  803. selector = selector.replace(/[+]/g, '_plus');
  804. selector = selector.replace(/-/g, '_minus');
  805. selector = selector.replace(/[*]/g ,'_star');
  806. selector = selector.replace(/[\/]/g ,'_slash');
  807. selector = selector.replace(/[\\]/g ,'_backslash');
  808. selector = selector.replace(/[\~]/g ,'_tild');
  809. selector = selector.replace(/>/g ,'_gt');
  810. selector = selector.replace(/</g ,'_lt');
  811. selector = selector.replace(/=/g ,'_eq');
  812. selector = selector.replace(/,/g ,'_comma');
  813. selector = selector.replace(/[@]/g ,'_at');
  814. return selector;
  815. };
  816. /* Convert a string to a valid smalltalk selector.
  817. if you modify the following functions, also change String>>asSelector
  818. accordingly */
  819. st.convertSelector = function(selector) {
  820. if(selector.match(/__/)) {
  821. return convertBinarySelector(selector);
  822. } else {
  823. return convertKeywordSelector(selector);
  824. }
  825. };
  826. function convertKeywordSelector(selector) {
  827. return selector.replace(/^_/, '').replace(/_/g, ':');
  828. }
  829. function convertBinarySelector(selector) {
  830. return selector
  831. .replace(/^_/, '')
  832. .replace(/_and/g, '&')
  833. .replace(/_or/g, '|')
  834. .replace(/_plus/g, '+')
  835. .replace(/_minus/g, '-')
  836. .replace(/_star/g, '*')
  837. .replace(/_slash/g, '/')
  838. .replace(/_backslash/g, '\\')
  839. .replace(/_tild/g, '~')
  840. .replace(/_gt/g, '>')
  841. .replace(/_lt/g, '<')
  842. .replace(/_eq/g, '=')
  843. .replace(/_comma/g, ',')
  844. .replace(/_at/g, '@');
  845. }
  846. }
  847. /* Adds AMD and requirejs related methods to the smalltalk object */
  848. function AMDBrik(brikz, st) {
  849. this.__init__ = function () {
  850. st.amdRequire = st.amdRequire || null;
  851. st.defaultTransportType = st.defaultTransportType || "amd";
  852. st.defaultAmdNamespace = st.defaultAmdNamespace || "amber_core";
  853. };
  854. }
  855. /* Making smalltalk that can load */
  856. brikz.root = RootBrik;
  857. brikz.dnu = DNUBrik;
  858. brikz.organize = OrganizeBrik;
  859. brikz.selectorConversion = SelectorConversionBrik;
  860. brikz.classInit = ClassInitBrik;
  861. brikz.manipulation = ManipulationBrik;
  862. brikz.classes = ClassesBrik;
  863. brikz.methods = MethodsBrik;
  864. brikz.stInit = SmalltalkInitBrik;
  865. brikz.augments = AugmentsBrik;
  866. brikz.amdBrik = AMDBrik;
  867. brikz.rebuild();
  868. /* Making smalltalk that can run */
  869. function runnable () {
  870. brikz.messageSend = MessageSendBrik;
  871. brikz.runtime = RuntimeBrik;
  872. brikz.primitives = PrimitivesBrik;
  873. brikz.rebuild();
  874. };
  875. return { smalltalk: api, nil: brikz.root.nil };
  876. });