1
0

boot.js 34 KB

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