2
0

boot.js 34 KB

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