1
0

boot.js 42 KB

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