boot.js 25 KB

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