boot.js 27 KB

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