boot.js 25 KB

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