1
0

boot.js 33 KB

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