1
0

boot.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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. throw error;
  486. }
  487. }
  488. };
  489. function inContext(worker, setup) {
  490. var context = pushContext(setup);
  491. var result = worker(context);
  492. popContext(context);
  493. return result;
  494. }
  495. /* Handles Smalltalk errors. Triggers the registered ErrorHandler
  496. (See the Smalltalk class ErrorHandler and its subclasses */
  497. function handleError(error) {
  498. st.ErrorHandler._current()._handleError_(error);
  499. }
  500. /* Handles #dnu: *and* JavaScript method calls.
  501. if the receiver has no klass, we consider it a JS object (outside of the
  502. Amber system). Else assume that the receiver understands #doesNotUnderstand: */
  503. function messageNotUnderstood(receiver, selector, args) {
  504. /* Handles JS method calls. */
  505. if(receiver.klass === undefined || receiver.allowJavaScriptCalls) {
  506. return callJavaScriptMethod(receiver, selector, args);
  507. }
  508. /* Handles not understood messages. Also see the Amber counter-part
  509. Object>>doesNotUnderstand: */
  510. return receiver._doesNotUnderstand_(
  511. st.Message._new()
  512. ._selector_(st.convertSelector(selector))
  513. ._arguments_(args)
  514. );
  515. }
  516. /* Call a method of a JS object, or answer a property if it exists.
  517. Else try wrapping a JSObjectProxy around the receiver.
  518. If the object property is a function, then call it, except if it starts with
  519. an uppercase character (we probably want to answer the function itself in this
  520. case and send it #new from Amber).
  521. Converts keyword-based selectors by using the first
  522. keyword only, but keeping all message arguments.
  523. Example:
  524. "self do: aBlock with: anObject" -> "self.do(aBlock, anObject)" */
  525. function callJavaScriptMethod(receiver, selector, args) {
  526. var jsSelector = selector._asJavaScriptSelector();
  527. var jsProperty = receiver[jsSelector];
  528. if(typeof jsProperty === "function" && !/^[A-Z]/.test(jsSelector)) {
  529. return jsProperty.apply(receiver, args);
  530. } else if(jsProperty !== undefined) {
  531. if(args[0]) {
  532. receiver[jsSelector] = args[0];
  533. return nil;
  534. } else {
  535. return jsProperty;
  536. }
  537. }
  538. return st.send(st.JSObjectProxy._on_(receiver), selector, args);
  539. }
  540. /* Handle thisContext pseudo variable */
  541. st.getThisContext = function() {
  542. if(st.thisContext) {
  543. st.thisContext.init();
  544. return st.thisContext;
  545. } else {
  546. return nil;
  547. }
  548. };
  549. function pushContext(setup) {
  550. return st.thisContext = new SmalltalkMethodContext(smalltalk.thisContext, setup);
  551. }
  552. function popContext(context) {
  553. st.thisContext = context.homeContext;
  554. }
  555. /* Convert a Smalltalk selector into a JS selector */
  556. st.selector = function(string) {
  557. var selector = '_' + string;
  558. selector = selector.replace(/:/g, '_');
  559. selector = selector.replace(/[\&]/g, '_and');
  560. selector = selector.replace(/[\|]/g, '_or');
  561. selector = selector.replace(/[+]/g, '_plus');
  562. selector = selector.replace(/-/g, '_minus');
  563. selector = selector.replace(/[*]/g ,'_star');
  564. selector = selector.replace(/[\/]/g ,'_slash');
  565. selector = selector.replace(/[\\]/g ,'_backslash');
  566. selector = selector.replace(/[\~]/g ,'_tild');
  567. selector = selector.replace(/>/g ,'_gt');
  568. selector = selector.replace(/</g ,'_lt');
  569. selector = selector.replace(/=/g ,'_eq');
  570. selector = selector.replace(/,/g ,'_comma');
  571. selector = selector.replace(/[@]/g ,'_at');
  572. return selector
  573. };
  574. /* Convert a string to a valid smalltalk selector.
  575. if you modify the following functions, also change String>>asSelector
  576. accordingly */
  577. st.convertSelector = function(selector) {
  578. if(selector.match(/__/)) {
  579. return convertBinarySelector(selector);
  580. } else {
  581. return convertKeywordSelector(selector);
  582. }
  583. };
  584. function convertKeywordSelector(selector) {
  585. return selector.replace(/^_/, '').replace(/_/g, ':');
  586. }
  587. function convertBinarySelector(selector) {
  588. return selector
  589. .replace(/^_/, '')
  590. .replace(/_and/g, '&')
  591. .replace(/_or/g, '|')
  592. .replace(/_plus/g, '+')
  593. .replace(/_minus/g, '-')
  594. .replace(/_star/g, '*')
  595. .replace(/_slash/g, '/')
  596. .replace(/_backslash/g, '\\')
  597. .replace(/_tild/g, '~')
  598. .replace(/_gt/g, '>')
  599. .replace(/_lt/g, '<')
  600. .replace(/_eq/g, '=')
  601. .replace(/_comma/g, ',')
  602. .replace(/_at/g, '@')
  603. }
  604. /* Converts a JavaScript object to valid Smalltalk Object */
  605. st.readJSObject = function(js) {
  606. var object = js;
  607. var readObject = (js.constructor === Object);
  608. var readArray = (js.constructor === Array);
  609. if(readObject) {
  610. object = st.Dictionary._new();
  611. }
  612. for(var i in js) {
  613. if(readObject) {
  614. object._at_put_(i, st.readJSObject(js[i]));
  615. }
  616. if(readArray) {
  617. object[i] = st.readJSObject(js[i]);
  618. }
  619. }
  620. return object;
  621. };
  622. /* Boolean assertion */
  623. st.assert = function(shouldBeBoolean) {
  624. if ((undefined !== shouldBeBoolean) && (shouldBeBoolean.klass === smalltalk.Boolean)) {
  625. return shouldBeBoolean == true;
  626. } else {
  627. smalltalk.NonBooleanReceiver._new()._object_(shouldBeBoolean)._signal();
  628. }
  629. };
  630. /* Backward compatibility with Amber 0.9.1 */
  631. st.symbolFor = function(aString) { return aString; }
  632. /* Smalltalk initialization. Called on page load */
  633. st.initialize = function() {
  634. if(initialized) { return; }
  635. classes.forEach(function(klass) {
  636. st.init(klass);
  637. });
  638. classes.forEach(function(klass) {
  639. klass._initialize();
  640. });
  641. initialized = true;
  642. };
  643. }
  644. inherits(Smalltalk, SmalltalkObject);
  645. function SmalltalkMethodContext(home, setup) {
  646. this.homeContext = home;
  647. this.setup = setup || function() {};
  648. this.pc = 0;
  649. }
  650. // Fallbacks
  651. SmalltalkMethodContext.prototype.locals = {};
  652. SmalltalkMethodContext.prototype.receiver = null;
  653. SmalltalkMethodContext.prototype.selector = null;
  654. SmalltalkMethodContext.prototype.lookupClass = null;
  655. inherits(SmalltalkMethodContext, SmalltalkObject);
  656. SmalltalkMethodContext.prototype.fill = function(receiver, selector, locals, lookupClass) {
  657. this.receiver = receiver;
  658. this.selector = selector;
  659. this.locals = locals || {};
  660. this.lookupClass = lookupClass;
  661. };
  662. SmalltalkMethodContext.prototype.fillBlock = function(locals, ctx) {
  663. this.locals = locals || {};
  664. this.outerContext = ctx;
  665. };
  666. SmalltalkMethodContext.prototype.init = function() {
  667. var home = this.homeContext;
  668. if(home) {home = home.init()}
  669. this.setup(this);
  670. };
  671. SmalltalkMethodContext.prototype.method = function() {
  672. var method;
  673. var lookup = this.lookupClass || this.receiver.klass;
  674. while(!method && lookup) {
  675. method = lookup.methods[smalltalk.convertSelector(this.selector)];
  676. lookup = lookup.superclass
  677. }
  678. return method;
  679. };
  680. // TODO: this is just wrong :)
  681. SmalltalkMethodContext.prototype.resume = function() {
  682. //Brutally set the receiver as thisContext, then re-enter the function
  683. smalltalk.thisContext = this;
  684. return this.method.apply(receiver, temps);
  685. };
  686. /* Global Smalltalk objects. */
  687. var nil = new SmalltalkNil();
  688. var smalltalk = new Smalltalk();
  689. if(this.jQuery) {
  690. this.jQuery.allowJavaScriptCalls = true;
  691. }
  692. /*
  693. * Answer the smalltalk representation of o.
  694. * Used in message sends
  695. */
  696. var _st = function(o) {
  697. if(o == null) {return nil}
  698. if(o.klass) {return o}
  699. return smalltalk.JSObjectProxy._on_(o);
  700. };
  701. /***************************************** BOOTSTRAP ******************************************/
  702. smalltalk.wrapClassName("Object", "Kernel-Objects", SmalltalkObject, undefined, false);
  703. smalltalk.wrapClassName("Behavior", "Kernel-Classes", SmalltalkBehavior, smalltalk.Object, false);
  704. smalltalk.wrapClassName("Metaclass", "Kernel-Classes", SmalltalkMetaclass, smalltalk.Behavior, false);
  705. smalltalk.wrapClassName("Class", "Kernel-Classes", SmalltalkClass, smalltalk.Behavior, false);
  706. smalltalk.Object.klass.superclass = smalltalk.Class;
  707. smalltalk.wrapClassName("Smalltalk", "Kernel-Objects", Smalltalk, smalltalk.Object, false);
  708. smalltalk.wrapClassName("Package", "Kernel-Objects", SmalltalkPackage, smalltalk.Object, false);
  709. smalltalk.wrapClassName("CompiledMethod", "Kernel-Methods", SmalltalkMethod, smalltalk.Object, false);
  710. smalltalk.wrapClassName("Organizer", "Kernel-Objects", SmalltalkOrganizer, smalltalk.Object, false);
  711. smalltalk.wrapClassName("PackageOrganizer", "Kernel-Objects", SmalltalkPackageOrganizer, smalltalk.Organizer, false);
  712. smalltalk.wrapClassName("ClassOrganizer", "Kernel-Objects", SmalltalkClassOrganizer, smalltalk.Organizer, false);
  713. smalltalk.wrapClassName("Number", "Kernel-Objects", Number, smalltalk.Object);
  714. smalltalk.wrapClassName("BlockClosure", "Kernel-Methods", Function, smalltalk.Object);
  715. smalltalk.wrapClassName("Boolean", "Kernel-Objects", Boolean, smalltalk.Object);
  716. smalltalk.wrapClassName("Date", "Kernel-Objects", Date, smalltalk.Object);
  717. smalltalk.wrapClassName("UndefinedObject", "Kernel-Objects", SmalltalkNil, smalltalk.Object, false);
  718. smalltalk.addClass("Collection", smalltalk.Object, null, "Kernel-Collections");
  719. smalltalk.addClass("IndexableCollection", smalltalk.Collection, null, "Kernel-Collections");
  720. smalltalk.addClass("SequenceableCollection", smalltalk.IndexableCollection, null, "Kernel-Collections");
  721. smalltalk.addClass("CharacterArray", smalltalk.SequenceableCollection, null, "Kernel-Collections");
  722. smalltalk.wrapClassName("String", "Kernel-Collections", String, smalltalk.CharacterArray);
  723. smalltalk.wrapClassName("Array", "Kernel-Collections", Array, smalltalk.SequenceableCollection);
  724. smalltalk.wrapClassName("RegularExpression", "Kernel-Collections", RegExp, smalltalk.Object);
  725. smalltalk.wrapClassName("Error", "Kernel-Exceptions", Error, smalltalk.Object);
  726. smalltalk.wrapClassName("MethodContext", "Kernel-Methods", SmalltalkMethodContext, smalltalk.Object, false);
  727. /* Alias definitions */
  728. smalltalk.alias(smalltalk.Array, "OrderedCollection");
  729. smalltalk.alias(smalltalk.Date, "Time");