boot.js 30 KB

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