boot.js 34 KB

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