1
0

boot.js 32 KB

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