2
0

boot.js 34 KB

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