boot.js 26 KB

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