boot.js 29 KB

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