1
0

boot.js 27 KB

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