boot.js 33 KB

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