2
0

boot.js 26 KB

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