1
0

boot.js 34 KB

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