1
0

boot.js 34 KB

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