2
0

boot.js 28 KB

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