2
0

boot.js 34 KB

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