boot.js 30 KB

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