boot.js 30 KB

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