boot.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  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-2016
  13. | The Amber team https://lolg.it/org/amber/members
  14. | Amber contributors (see /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://lolg.it/herby/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. st.addPackage("Kernel-Promises");
  628. st.addClass("Thenable", globals.Object, null, "Kernel-Promises");
  629. st.wrapClassName("Promise", "Kernel-Promises", Promise, globals.Thenable);
  630. /* Alias definitions */
  631. st.alias(globals.Array, "OrderedCollection");
  632. st.alias(globals.Date, "Time");
  633. };
  634. }
  635. function PrimitivesBrik(brikz, st) {
  636. /* Unique ID number generator */
  637. var oid = 0;
  638. st.nextId = function () {
  639. oid += 1;
  640. return oid;
  641. };
  642. /* Converts a JavaScript object to valid Smalltalk Object */
  643. st.readJSObject = function (js) {
  644. if (js == null)
  645. return null;
  646. var readObject = js.constructor === Object;
  647. var readArray = js.constructor === Array;
  648. var object = readObject ? globals.Dictionary._new() : readArray ? [] : js;
  649. for (var i in js) {
  650. if (readObject) {
  651. object._at_put_(i, st.readJSObject(js[i]));
  652. }
  653. if (readArray) {
  654. object[i] = st.readJSObject(js[i]);
  655. }
  656. }
  657. return object;
  658. };
  659. /* Boolean assertion */
  660. st.assert = function (shouldBeBoolean) {
  661. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  662. else if (shouldBeBoolean != null && typeof shouldBeBoolean === "object") {
  663. shouldBeBoolean = shouldBeBoolean.valueOf();
  664. if (typeof shouldBeBoolean === "boolean") return shouldBeBoolean;
  665. }
  666. globals.NonBooleanReceiver._new()._object_(shouldBeBoolean)._signal();
  667. };
  668. /* List of all reserved words in JavaScript. They may not be used as variables
  669. in Smalltalk. */
  670. // list of reserved JavaScript keywords as of
  671. // http://es5.github.com/#x7.6.1.1
  672. // and
  673. // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.6.1
  674. st.reservedWords = ['break', 'case', 'catch', 'continue', 'debugger',
  675. 'default', 'delete', 'do', 'else', 'finally', 'for', 'function',
  676. 'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', 'throw',
  677. 'try', 'typeof', 'var', 'void', 'while', 'with',
  678. // Amber protected words: these should not be compiled as-is when in code
  679. 'arguments',
  680. // ES5: future use: http://es5.github.com/#x7.6.1.2
  681. 'class', 'const', 'enum', 'export', 'extends', 'import', 'super',
  682. // ES5: future use in strict mode
  683. 'implements', 'interface', 'let', 'package', 'private', 'protected',
  684. 'public', 'static', 'yield'];
  685. st.globalJsVariables = ['window', 'document', 'process', 'global'];
  686. }
  687. function RuntimeBrik(brikz, st) {
  688. brikz.ensure("selectorConversion");
  689. var root = brikz.ensure("root");
  690. var nil = root.nil;
  691. var SmalltalkObject = root.Object;
  692. function SmalltalkMethodContext(home, setup) {
  693. this.sendIdx = {};
  694. this.homeContext = home;
  695. this.setup = setup || function () {
  696. };
  697. this.supercall = false;
  698. }
  699. inherits(SmalltalkMethodContext, SmalltalkObject);
  700. this.__init__ = function () {
  701. st.addPackage("Kernel-Methods");
  702. st.wrapClassName("MethodContext", "Kernel-Methods", SmalltalkMethodContext, globals.Object, false);
  703. // Fallbacks
  704. SmalltalkMethodContext.prototype.locals = {};
  705. SmalltalkMethodContext.prototype.receiver = null;
  706. SmalltalkMethodContext.prototype.selector = null;
  707. SmalltalkMethodContext.prototype.lookupClass = null;
  708. SmalltalkMethodContext.prototype.fill = function (receiver, selector, locals, lookupClass) {
  709. this.receiver = receiver;
  710. this.selector = selector;
  711. this.locals = locals || {};
  712. this.lookupClass = lookupClass;
  713. if (this.homeContext) {
  714. this.homeContext.evaluatedSelector = selector;
  715. }
  716. };
  717. SmalltalkMethodContext.prototype.fillBlock = function (locals, ctx, index) {
  718. this.locals = locals || {};
  719. this.outerContext = ctx;
  720. this.index = index || 0;
  721. };
  722. SmalltalkMethodContext.prototype.init = function () {
  723. var home = this.homeContext;
  724. if (home) {
  725. home.init();
  726. }
  727. this.setup(this);
  728. };
  729. SmalltalkMethodContext.prototype.method = function () {
  730. var method;
  731. var lookup = this.lookupClass || this.receiver.klass;
  732. while (!method && lookup) {
  733. method = lookup.methods[st.js2st(this.selector)];
  734. lookup = lookup.superclass;
  735. }
  736. return method;
  737. };
  738. };
  739. /* This is the current call context object. While it is publicly available,
  740. Use smalltalk.getThisContext() instead which will answer a safe copy of
  741. the current context */
  742. var thisContext = null;
  743. st.withContext = function (worker, setup) {
  744. if (thisContext) {
  745. return inContext(worker, setup);
  746. } else {
  747. return inContextWithErrorHandling(worker, setup);
  748. }
  749. };
  750. /*
  751. Runs worker function so that error handler is not set up
  752. if there isn't one. This is accomplished by unconditional
  753. wrapping inside a context of a simulated `nil seamlessDoIt` call,
  754. which then stops error handler setup (see st.withContext above).
  755. The effect is, $core.seamless(fn)'s exceptions are not
  756. handed into ST error handler and caller should process them.
  757. */
  758. st.seamless = function (worker) {
  759. return inContext(worker, function (ctx) {
  760. ctx.fill(nil, "seamlessDoIt", {}, globals.UndefinedObject);
  761. });
  762. };
  763. function inContextWithErrorHandling(worker, setup) {
  764. try {
  765. return inContext(worker, setup);
  766. } catch (error) {
  767. handleError(error);
  768. thisContext = null;
  769. // Rethrow the error in any case.
  770. error.amberHandled = true;
  771. throw error;
  772. }
  773. }
  774. function inContext(worker, setup) {
  775. var oldContext = thisContext;
  776. thisContext = new SmalltalkMethodContext(thisContext, setup);
  777. var result = worker(thisContext);
  778. thisContext = oldContext;
  779. return result;
  780. }
  781. /* Wrap a JavaScript exception in a Smalltalk Exception.
  782. In case of a RangeError, stub the stack after 100 contexts to
  783. avoid another RangeError later when the stack is manipulated. */
  784. function wrappedError(error) {
  785. var errorWrapper = globals.JavaScriptException._on_(error);
  786. // Add the error to the context, so it is visible in the stack
  787. try {
  788. errorWrapper._signal();
  789. } catch (ex) {
  790. }
  791. var context = st.getThisContext();
  792. if (isRangeError(error)) {
  793. stubContextStack(context);
  794. }
  795. errorWrapper._context_(context);
  796. return errorWrapper;
  797. }
  798. /* Stub the context stack after 100 contexts */
  799. function stubContextStack(context) {
  800. var currentContext = context;
  801. var contexts = 0;
  802. while (contexts < 100) {
  803. if (currentContext) {
  804. currentContext = currentContext.homeContext;
  805. }
  806. contexts++;
  807. }
  808. if (currentContext) {
  809. currentContext.homeContext = undefined;
  810. }
  811. }
  812. function isRangeError(error) {
  813. return error instanceof RangeError;
  814. }
  815. /* Handles Smalltalk errors. Triggers the registered ErrorHandler
  816. (See the Smalltalk class ErrorHandler and its subclasses */
  817. function handleError(error) {
  818. if (!error.smalltalkError) {
  819. error = wrappedError(error);
  820. }
  821. globals.ErrorHandler._handleError_(error);
  822. }
  823. /* Handle thisContext pseudo variable */
  824. st.getThisContext = function () {
  825. if (thisContext) {
  826. thisContext.init();
  827. return thisContext;
  828. } else {
  829. return nil;
  830. }
  831. };
  832. }
  833. function MessageSendBrik(brikz, st) {
  834. brikz.ensure("selectorConversion");
  835. var nil = brikz.ensure("root").nil;
  836. /* Handles unhandled errors during message sends */
  837. // simply send the message and handle #dnu:
  838. st.send = function (receiver, jsSelector, args, klass) {
  839. var method;
  840. if (receiver == null) {
  841. receiver = nil;
  842. }
  843. method = klass ? klass.fn.prototype[jsSelector] : receiver.klass && receiver[jsSelector];
  844. if (method) {
  845. return method.apply(receiver, args || []);
  846. } else {
  847. return messageNotUnderstood(receiver, st.js2st(jsSelector), args);
  848. }
  849. };
  850. function invokeDnuMethod(receiver, stSelector, args) {
  851. return receiver._doesNotUnderstand_(
  852. globals.Message._new()
  853. ._selector_(stSelector)
  854. ._arguments_([].slice.call(args))
  855. );
  856. }
  857. /* Handles #dnu: *and* JavaScript method calls.
  858. if the receiver has no klass, we consider it a JS object (outside of the
  859. Amber system). Else assume that the receiver understands #doesNotUnderstand: */
  860. function messageNotUnderstood(receiver, stSelector, args) {
  861. if (receiver.klass != null && !receiver.allowJavaScriptCalls) {
  862. return invokeDnuMethod(receiver, stSelector, args);
  863. }
  864. /* Call a method of a JS object, or answer a property if it exists.
  865. Else try wrapping a JSObjectProxy around the receiver. */
  866. var propertyName = st.st2prop(stSelector);
  867. if (!(propertyName in receiver)) {
  868. return invokeDnuMethod(globals.JSObjectProxy._on_(receiver), stSelector, args);
  869. }
  870. return accessJavaScript(receiver, propertyName, args);
  871. }
  872. /* If the object property is a function, then call it, except if it starts with
  873. an uppercase character (we probably want to answer the function itself in this
  874. case and send it #new from Amber).
  875. Converts keyword-based selectors by using the first
  876. keyword only, but keeping all message arguments.
  877. Example:
  878. "self do: aBlock with: anObject" -> "self.do(aBlock, anObject)" */
  879. function accessJavaScript(receiver, propertyName, args) {
  880. var propertyValue = receiver[propertyName];
  881. if (typeof propertyValue === "function" && !/^[A-Z]/.test(propertyName)) {
  882. return propertyValue.apply(receiver, args || []);
  883. } else if (args.length > 0) {
  884. receiver[propertyName] = args[0];
  885. return nil;
  886. } else {
  887. return propertyValue;
  888. }
  889. }
  890. st.accessJavaScript = accessJavaScript;
  891. this.messageNotUnderstood = messageNotUnderstood;
  892. }
  893. function SelectorConversionBrik(brikz, st) {
  894. /* Convert a Smalltalk selector into a JS selector */
  895. st.st2js = function (string) {
  896. var selector = '_' + string;
  897. selector = selector.replace(/:/g, '_');
  898. selector = selector.replace(/[\&]/g, '_and');
  899. selector = selector.replace(/[\|]/g, '_or');
  900. selector = selector.replace(/[+]/g, '_plus');
  901. selector = selector.replace(/-/g, '_minus');
  902. selector = selector.replace(/[*]/g, '_star');
  903. selector = selector.replace(/[\/]/g, '_slash');
  904. selector = selector.replace(/[\\]/g, '_backslash');
  905. selector = selector.replace(/[\~]/g, '_tild');
  906. selector = selector.replace(/>/g, '_gt');
  907. selector = selector.replace(/</g, '_lt');
  908. selector = selector.replace(/=/g, '_eq');
  909. selector = selector.replace(/,/g, '_comma');
  910. selector = selector.replace(/[@]/g, '_at');
  911. return selector;
  912. };
  913. /* Convert a string to a valid smalltalk selector.
  914. if you modify the following functions, also change st2js
  915. accordingly */
  916. st.js2st = function (selector) {
  917. if (selector.match(/^__/)) {
  918. return binaryJsToSt(selector);
  919. } else {
  920. return keywordJsToSt(selector);
  921. }
  922. };
  923. function keywordJsToSt(selector) {
  924. return selector.replace(/^_/, '').replace(/_/g, ':');
  925. }
  926. function binaryJsToSt(selector) {
  927. return selector
  928. .replace(/^_/, '')
  929. .replace(/_and/g, '&')
  930. .replace(/_or/g, '|')
  931. .replace(/_plus/g, '+')
  932. .replace(/_minus/g, '-')
  933. .replace(/_star/g, '*')
  934. .replace(/_slash/g, '/')
  935. .replace(/_backslash/g, '\\')
  936. .replace(/_tild/g, '~')
  937. .replace(/_gt/g, '>')
  938. .replace(/_lt/g, '<')
  939. .replace(/_eq/g, '=')
  940. .replace(/_comma/g, ',')
  941. .replace(/_at/g, '@');
  942. }
  943. st.st2prop = function (stSelector) {
  944. var colonPosition = stSelector.indexOf(':');
  945. return colonPosition === -1 ? stSelector : stSelector.slice(0, colonPosition);
  946. };
  947. }
  948. /* Adds AMD and requirejs related methods to the smalltalk object */
  949. function AMDBrik(brikz, st) {
  950. this.__init__ = function () {
  951. st.amdRequire = require;
  952. st.defaultTransportType = st.defaultTransportType || "amd";
  953. st.defaultAmdNamespace = st.defaultAmdNamespace || "amber_core";
  954. };
  955. }
  956. /* Defines asReceiver to be present at load time */
  957. /* (logically it belongs more to PrimitiveBrik) */
  958. function AsReceiverBrik(brikz, st) {
  959. var nil = brikz.ensure("root").nil;
  960. /**
  961. * This function is used all over the compiled amber code.
  962. * It takes any value (JavaScript or Smalltalk)
  963. * and returns a proper Amber Smalltalk receiver.
  964. *
  965. * null or undefined -> nil,
  966. * plain JS object -> wrapped JS object,
  967. * otherwise unchanged
  968. */
  969. this.asReceiver = function (o) {
  970. if (o == null) return nil;
  971. if (typeof o === "object" || typeof o === "function") {
  972. return o.klass != null ? o : globals.JSObjectProxy._on_(o);
  973. }
  974. // IMPORTANT: This optimization (return o if typeof !== "object")
  975. // assumes all primitive types are wrapped by some Smalltalk class
  976. // so they can be returned as-is, without boxing and looking for .klass.
  977. // KEEP THE primitives-are-wrapped INVARIANT!
  978. return o;
  979. };
  980. }
  981. /* Making smalltalk that can load */
  982. brikz.root = RootBrik;
  983. brikz.dnu = DNUBrik;
  984. brikz.organize = OrganizeBrik;
  985. brikz.selectorConversion = SelectorConversionBrik;
  986. brikz.classInit = ClassInitBrik;
  987. brikz.manipulation = ManipulationBrik;
  988. brikz.packages = PackagesBrik;
  989. brikz.classes = ClassesBrik;
  990. brikz.methods = MethodsBrik;
  991. brikz.stInit = SmalltalkInitBrik;
  992. brikz.augments = AugmentsBrik;
  993. brikz.asReceiver = AsReceiverBrik;
  994. brikz.amd = AMDBrik;
  995. brikz.rebuild();
  996. /* Making smalltalk that can run */
  997. function runnable() {
  998. brikz.messageSend = MessageSendBrik;
  999. brikz.runtime = RuntimeBrik;
  1000. brikz.primitives = PrimitivesBrik;
  1001. brikz.rebuild();
  1002. }
  1003. return {
  1004. api: api,
  1005. nil: brikz.root.nil,
  1006. dnu: brikz.root.rootAsClass,
  1007. globals: globals,
  1008. asReceiver: brikz.asReceiver.asReceiver
  1009. };
  1010. });