boot.js 42 KB

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