1
0

boot.js 34 KB

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