boot.js 29 KB

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