boot.js 25 KB

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