1
0

boot.js 34 KB

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