1
0

boot.js 34 KB

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