boot.js 42 KB

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