2
0

boot.js 29 KB

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