boot.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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. } else {
  228. installSuperclass(klass);
  229. }
  230. if(klass === st.Object || klass.wrapped) {
  231. installDnuHandlers(klass);
  232. }
  233. };
  234. function wireKlass(klass) {
  235. Object.defineProperty(klass.fn.prototype, "klass", {
  236. value: klass,
  237. enumerable: false, configurable: true, writable: true
  238. });
  239. }
  240. function installSuperclass(klass) {
  241. // only if the klass has not been initialized yet.
  242. if(klass.fn.prototype._yourself) { return; }
  243. if(klass.superclass && klass.superclass !== nil) {
  244. inherits(klass.fn, klass.superclass.fn);
  245. wireKlass(klass);
  246. reinstallMethods(klass);
  247. }
  248. }
  249. function copySuperclass(klass, superclass) {
  250. for (superclass = superclass || klass.superclass;
  251. superclass && superclass !== nil;
  252. superclass = superclass.superclass) {
  253. for (var keys = Object.keys(superclass.methods), i = 0; i < keys.length; i++) {
  254. installMethodIfAbsent(superclass.methods[keys[i]], klass);
  255. }
  256. }
  257. }
  258. function installMethod(method, klass) {
  259. Object.defineProperty(klass.fn.prototype, method.jsSelector, {
  260. value: method.fn,
  261. enumerable: false, configurable: true, writable: true
  262. });
  263. }
  264. function installMethodIfAbsent(method, klass) {
  265. if(!klass.fn.prototype[method.jsSelector]) {
  266. installMethod(method, klass);
  267. }
  268. }
  269. function reinstallMethods(klass) {
  270. for(var keys = Object.keys(klass.methods), i=0; i<keys.length; i++) {
  271. installMethod(klass.methods[keys[i]], klass);
  272. }
  273. }
  274. function installDnuHandlers(klass) {
  275. var m = dnu.methods;
  276. for(var i=0; i<m.length; i++) {
  277. installMethodIfAbsent(m[i], klass);
  278. }
  279. }
  280. function installNewDnuHandler(newHandler) {
  281. installMethodIfAbsent(newHandler, st.Object);
  282. for(var i = 0; i < wrappedClasses.length; i++) {
  283. installMethodIfAbsent(newHandler, wrappedClasses[i]);
  284. }
  285. }
  286. /* Answer all registered Packages as Array */
  287. // TODO: Remove this hack
  288. st.packages.all = function() {
  289. var packages = [];
  290. for(var i in st.packages) {
  291. if(!st.packages.hasOwnProperty(i) || typeof(st.packages[i]) === "function") continue;
  292. packages.push(st.packages[i]);
  293. }
  294. return packages;
  295. };
  296. /* Answer all registered Smalltalk classes */
  297. //TODO: remove the function and make smalltalk.classes an array
  298. st.classes = function() {
  299. return classes;
  300. };
  301. st.wrappedClasses = function() {
  302. return wrappedClasses;
  303. };
  304. /* Answer the direct subclasses of klass. */
  305. st.subclasses = function(klass) {
  306. var subclasses = [];
  307. var classes = st.classes();
  308. for(var i=0; i < classes.length; i++) {
  309. var c = classes[i];
  310. if(c.fn) {
  311. //Classes
  312. if(c.superclass === klass) {
  313. subclasses.push(c);
  314. }
  315. c = c.klass;
  316. //Metaclasses
  317. if(c && c.superclass === klass) {
  318. subclasses.push(c);
  319. }
  320. }
  321. }
  322. return subclasses;
  323. };
  324. st.allSubclasses = function(klass) {
  325. var result, subclasses;
  326. result = subclasses = st.subclasses(klass);
  327. subclasses.forEach(function(subclass) {
  328. result.push.apply(result, st.allSubclasses(subclass));
  329. });
  330. return result;
  331. };
  332. /* Create a new class wrapping a JavaScript constructor, and add it to the
  333. global smalltalk object. Package is lazily created if it does not exist with given name. */
  334. st.wrapClassName = function(className, pkgName, fn, superclass, wrapped) {
  335. if(wrapped !== false) {
  336. wrapped = true;
  337. }
  338. var pkg = st.addPackage(pkgName);
  339. st[className] = klass({
  340. className: className,
  341. superclass: superclass,
  342. pkg: pkg,
  343. fn: fn,
  344. wrapped: wrapped
  345. });
  346. classes.addElement(st[className]);
  347. if(wrapped) {
  348. wrappedClasses.addElement(st[className]);
  349. }
  350. pkg.organization.elements.addElement(st[className]);
  351. };
  352. /* Create an alias for an existing class */
  353. st.alias = function(klass, alias) {
  354. st[alias] = klass;
  355. };
  356. /* Add a package to the smalltalk.packages object, creating a new one if needed.
  357. If pkgName is null or empty we return nil, which is an allowed package for a class.
  358. If package already exists we still update the properties of it. */
  359. st.addPackage = function(pkgName, properties) {
  360. if(!pkgName) {return nil;}
  361. if(!(st.packages[pkgName])) {
  362. st.packages[pkgName] = pkg({
  363. pkgName: pkgName,
  364. properties: properties
  365. });
  366. } else {
  367. if(properties) {
  368. st.packages[pkgName].properties = properties;
  369. }
  370. }
  371. return st.packages[pkgName];
  372. };
  373. /* Add a class to the smalltalk object, creating a new one if needed.
  374. A Package is lazily created if it does not exist with given name. */
  375. st.addClass = function(className, superclass, iVarNames, pkgName) {
  376. var pkg = st.addPackage(pkgName);
  377. if (superclass == nil) { superclass = null; }
  378. if(st[className] && st[className].superclass == superclass) {
  379. st[className].superclass = superclass;
  380. st[className].iVarNames = iVarNames;
  381. st[className].pkg = pkg || st[className].pkg;
  382. } else {
  383. if(st[className]) {
  384. st.removeClass(st[className]);
  385. }
  386. st[className] = klass({
  387. className: className,
  388. superclass: superclass,
  389. pkg: pkg,
  390. iVarNames: iVarNames
  391. });
  392. }
  393. classes.addElement(st[className]);
  394. pkg.organization.elements.addElement(st[className]);
  395. };
  396. st.removeClass = function(klass) {
  397. klass.pkg.organization.elements.removeElement(klass);
  398. classes.removeElement(klass);
  399. delete st[klass.className];
  400. };
  401. /* Add/remove a method to/from a class */
  402. /* This is a temporary version of addMethod() for backward compatibility */
  403. st.addMethod = function(method_exJsSelector, klass_exMethod, exKlass) {
  404. if (typeof method_exJsSelector === "string") { //legacy
  405. if (method_exJsSelector !== st.selector(klass_exMethod.selector)) {
  406. console.log("DISCREPANCY: arg, in_method");
  407. console.log(method_exJsSelector);
  408. console.log(st.selector(klass_exMethod.selector));
  409. klass_exMethod.jsSelector = method_exJsSelector;
  410. }
  411. return new_addMethod(klass_exMethod, exKlass);
  412. }
  413. return new_addMethod(method_exJsSelector, klass_exMethod);
  414. };
  415. // later, st.addMethod can be this:
  416. function new_addMethod(method, klass) {
  417. if (!(method.jsSelector)) {
  418. method.jsSelector = st.selector(method.selector);
  419. }
  420. installMethod(method, klass);
  421. klass.methods[method.selector] = method;
  422. method.methodClass = klass;
  423. // During the bootstrap, #addCompiledMethod is not used.
  424. // Therefore we populate the organizer here too
  425. klass.organization.elements.addElement(method.category);
  426. // If already initialized (else it will be done later anyway),
  427. // re-initialize all subclasses to ensure the new method
  428. // propagation (for wrapped classes, not using the prototype
  429. // chain.
  430. if(initialized) {
  431. st.allSubclasses(klass).forEach(function(subclass) {
  432. st.initClass(subclass);
  433. });
  434. }
  435. for(var i=0; i<method.messageSends.length; i++) {
  436. var dnuHandler = dnu.get(method.messageSends[i]);
  437. if(initialized) {
  438. installNewDnuHandler(dnuHandler);
  439. }
  440. }
  441. }
  442. st.removeMethod = function(method) {
  443. var protocol = method.category;
  444. var klass = method.methodClass;
  445. delete klass.fn.prototype[st.selector(method.selector)];
  446. delete klass.methods[method.selector];
  447. var selectors = Object.keys(klass.methods);
  448. // Do *not* delete protocols from here.
  449. // This is handled by #removeCompiledMethod
  450. };
  451. /* Handles unhandled errors during message sends */
  452. // simply send the message and handle #dnu:
  453. st.send = function(receiver, selector, args, klass) {
  454. var method;
  455. if(receiver === null) {
  456. receiver = nil;
  457. }
  458. method = klass ? klass.fn.prototype[selector] : receiver.klass && receiver[selector];
  459. if(method) {
  460. return method.apply(receiver, args);
  461. } else {
  462. return messageNotUnderstood(receiver, selector, args);
  463. }
  464. };
  465. st.withContext = function(worker, setup) {
  466. if(st.thisContext) {
  467. st.thisContext.pc++;
  468. return inContext(worker, setup);
  469. } else {
  470. try {
  471. 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. st.thisContext = new SmalltalkMethodContext(smalltalk.thisContext, setup);
  552. return st.thisContext;
  553. }
  554. function popContext(context) {
  555. st.thisContext = context.homeContext;
  556. }
  557. /* Convert a Smalltalk selector into a JS selector */
  558. st.selector = function(string) {
  559. var selector = '_' + string;
  560. selector = selector.replace(/:/g, '_');
  561. selector = selector.replace(/[\&]/g, '_and');
  562. selector = selector.replace(/[\|]/g, '_or');
  563. selector = selector.replace(/[+]/g, '_plus');
  564. selector = selector.replace(/-/g, '_minus');
  565. selector = selector.replace(/[*]/g ,'_star');
  566. selector = selector.replace(/[\/]/g ,'_slash');
  567. selector = selector.replace(/[\\]/g ,'_backslash');
  568. selector = selector.replace(/[\~]/g ,'_tild');
  569. selector = selector.replace(/>/g ,'_gt');
  570. selector = selector.replace(/</g ,'_lt');
  571. selector = selector.replace(/=/g ,'_eq');
  572. selector = selector.replace(/,/g ,'_comma');
  573. selector = selector.replace(/[@]/g ,'_at');
  574. return selector;
  575. };
  576. /* Convert a string to a valid smalltalk selector.
  577. if you modify the following functions, also change String>>asSelector
  578. accordingly */
  579. st.convertSelector = function(selector) {
  580. if(selector.match(/__/)) {
  581. return convertBinarySelector(selector);
  582. } else {
  583. return convertKeywordSelector(selector);
  584. }
  585. };
  586. function convertKeywordSelector(selector) {
  587. return selector.replace(/^_/, '').replace(/_/g, ':');
  588. }
  589. function convertBinarySelector(selector) {
  590. return selector
  591. .replace(/^_/, '')
  592. .replace(/_and/g, '&')
  593. .replace(/_or/g, '|')
  594. .replace(/_plus/g, '+')
  595. .replace(/_minus/g, '-')
  596. .replace(/_star/g, '*')
  597. .replace(/_slash/g, '/')
  598. .replace(/_backslash/g, '\\')
  599. .replace(/_tild/g, '~')
  600. .replace(/_gt/g, '>')
  601. .replace(/_lt/g, '<')
  602. .replace(/_eq/g, '=')
  603. .replace(/_comma/g, ',')
  604. .replace(/_at/g, '@');
  605. }
  606. /* Converts a JavaScript object to valid Smalltalk Object */
  607. st.readJSObject = function(js) {
  608. var object = js;
  609. var readObject = (js.constructor === Object);
  610. var readArray = (js.constructor === Array);
  611. if(readObject) {
  612. object = st.Dictionary._new();
  613. }
  614. for(var i in js) {
  615. if(readObject) {
  616. object._at_put_(i, st.readJSObject(js[i]));
  617. }
  618. if(readArray) {
  619. object[i] = st.readJSObject(js[i]);
  620. }
  621. }
  622. return object;
  623. };
  624. /* Boolean assertion */
  625. st.assert = function(shouldBeBoolean) {
  626. if ((undefined !== shouldBeBoolean) && (shouldBeBoolean.klass === smalltalk.Boolean)) {
  627. return (shouldBeBoolean == true);
  628. } else {
  629. smalltalk.NonBooleanReceiver._new()._object_(shouldBeBoolean)._signal();
  630. }
  631. };
  632. /* Backward compatibility with Amber 0.9.1 */
  633. st.symbolFor = function(aString) { return aString; };
  634. /* Smalltalk initialization. Called on page load */
  635. st.initialize = function() {
  636. if(initialized) { return; }
  637. classes.forEach(function(klass) {
  638. st.init(klass);
  639. });
  640. classes.forEach(function(klass) {
  641. klass._initialize();
  642. });
  643. initialized = true;
  644. };
  645. }
  646. inherits(Smalltalk, SmalltalkObject);
  647. function SmalltalkMethodContext(home, setup) {
  648. this.homeContext = home;
  649. this.setup = setup || function() {};
  650. this.pc = 0;
  651. }
  652. // Fallbacks
  653. SmalltalkMethodContext.prototype.locals = {};
  654. SmalltalkMethodContext.prototype.receiver = null;
  655. SmalltalkMethodContext.prototype.selector = null;
  656. SmalltalkMethodContext.prototype.lookupClass = null;
  657. inherits(SmalltalkMethodContext, SmalltalkObject);
  658. SmalltalkMethodContext.prototype.fill = function(receiver, selector, locals, lookupClass) {
  659. this.receiver = receiver;
  660. this.selector = selector;
  661. this.locals = locals || {};
  662. this.lookupClass = lookupClass;
  663. };
  664. SmalltalkMethodContext.prototype.fillBlock = function(locals, ctx) {
  665. this.locals = locals || {};
  666. this.outerContext = ctx;
  667. };
  668. SmalltalkMethodContext.prototype.init = function() {
  669. var home = this.homeContext;
  670. if(home) {
  671. home = home.init();
  672. }
  673. this.setup(this);
  674. };
  675. SmalltalkMethodContext.prototype.method = function() {
  676. var method;
  677. var lookup = this.lookupClass || this.receiver.klass;
  678. while(!method && lookup) {
  679. method = lookup.methods[smalltalk.convertSelector(this.selector)];
  680. lookup = lookup.superclass;
  681. }
  682. return method;
  683. };
  684. // TODO: this is just wrong :)
  685. SmalltalkMethodContext.prototype.resume = function() {
  686. //Brutally set the receiver as thisContext, then re-enter the function
  687. smalltalk.thisContext = this;
  688. return this.method.apply(receiver, temps);
  689. };
  690. /* Global Smalltalk objects. */
  691. var nil = new SmalltalkNil();
  692. var smalltalk = new Smalltalk();
  693. if(this.jQuery) {
  694. this.jQuery.allowJavaScriptCalls = true;
  695. }
  696. /*
  697. * Answer the smalltalk representation of o.
  698. * Used in message sends
  699. */
  700. var _st = function(o) {
  701. if(o == null) {return nil;}
  702. if(o.klass) {return o;}
  703. return smalltalk.JSObjectProxy._on_(o);
  704. };
  705. /***************************************** BOOTSTRAP ******************************************/
  706. smalltalk.wrapClassName("Object", "Kernel-Objects", SmalltalkObject, undefined, false);
  707. smalltalk.wrapClassName("Behavior", "Kernel-Classes", SmalltalkBehavior, smalltalk.Object, false);
  708. smalltalk.wrapClassName("Metaclass", "Kernel-Classes", SmalltalkMetaclass, smalltalk.Behavior, false);
  709. smalltalk.wrapClassName("Class", "Kernel-Classes", SmalltalkClass, smalltalk.Behavior, false);
  710. smalltalk.Object.klass.superclass = smalltalk.Class;
  711. smalltalk.wrapClassName("Smalltalk", "Kernel-Objects", Smalltalk, smalltalk.Object, false);
  712. smalltalk.wrapClassName("Package", "Kernel-Objects", SmalltalkPackage, smalltalk.Object, false);
  713. smalltalk.wrapClassName("CompiledMethod", "Kernel-Methods", SmalltalkMethod, smalltalk.Object, false);
  714. smalltalk.wrapClassName("Organizer", "Kernel-Objects", SmalltalkOrganizer, smalltalk.Object, false);
  715. smalltalk.wrapClassName("PackageOrganizer", "Kernel-Objects", SmalltalkPackageOrganizer, smalltalk.Organizer, false);
  716. smalltalk.wrapClassName("ClassOrganizer", "Kernel-Objects", SmalltalkClassOrganizer, smalltalk.Organizer, false);
  717. smalltalk.wrapClassName("Number", "Kernel-Objects", Number, smalltalk.Object);
  718. smalltalk.wrapClassName("BlockClosure", "Kernel-Methods", Function, smalltalk.Object);
  719. smalltalk.wrapClassName("Boolean", "Kernel-Objects", Boolean, smalltalk.Object);
  720. smalltalk.wrapClassName("Date", "Kernel-Objects", Date, smalltalk.Object);
  721. smalltalk.wrapClassName("UndefinedObject", "Kernel-Objects", SmalltalkNil, smalltalk.Object, false);
  722. smalltalk.addClass("Collection", smalltalk.Object, null, "Kernel-Collections");
  723. smalltalk.addClass("IndexableCollection", smalltalk.Collection, null, "Kernel-Collections");
  724. smalltalk.addClass("SequenceableCollection", smalltalk.IndexableCollection, null, "Kernel-Collections");
  725. smalltalk.addClass("CharacterArray", smalltalk.SequenceableCollection, null, "Kernel-Collections");
  726. smalltalk.wrapClassName("String", "Kernel-Collections", String, smalltalk.CharacterArray);
  727. smalltalk.wrapClassName("Array", "Kernel-Collections", Array, smalltalk.SequenceableCollection);
  728. smalltalk.wrapClassName("RegularExpression", "Kernel-Collections", RegExp, smalltalk.Object);
  729. smalltalk.wrapClassName("Error", "Kernel-Exceptions", Error, smalltalk.Object);
  730. smalltalk.wrapClassName("MethodContext", "Kernel-Methods", SmalltalkMethodContext, smalltalk.Object, false);
  731. /* Alias definitions */
  732. smalltalk.alias(smalltalk.Array, "OrderedCollection");
  733. smalltalk.alias(smalltalk.Date, "Time");