boot.js 33 KB

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