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