2
0

boot.js 42 KB

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