boot.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. /* Smalltalk constructors definition */
  45. function SmalltalkObject(){};
  46. function SmalltalkBehavior(){};
  47. function SmalltalkClass(){};
  48. function SmalltalkPackage(){};
  49. function SmalltalkMetaclass(){
  50. this.meta = true;
  51. };
  52. function SmalltalkMethod(){};
  53. function SmalltalkNil(){};
  54. function SmalltalkSymbol(string){
  55. this.value = string;
  56. };
  57. function SmalltalkOrganizer() {
  58. this.elements = [];
  59. };
  60. SmalltalkOrganizer.prototype.addElement = function(el) {
  61. if(typeof el === 'undefined' || el === nil) {
  62. return false;
  63. }
  64. if(this.elements.indexOf(el) == -1) {
  65. this.elements.push(el);
  66. }
  67. };
  68. SmalltalkOrganizer.prototype.removeElement = function(el) {
  69. for(var i=0; i<this.elements.length; i++) {
  70. if(this.elements[i] == el) {
  71. this.elements.splice(i, 1);
  72. break;
  73. }
  74. }
  75. };
  76. function Smalltalk(){
  77. var st = this;
  78. /* This is the current call context object. While it is publicly available,
  79. Use smalltalk.getThisContext() instead which will answer a safe copy of
  80. the current context */
  81. st.thisContext = undefined;
  82. /* List of all reserved words in JavaScript. They may not be used as variables
  83. in Smalltalk. */
  84. st.reservedWords = ['break', 'case', 'catch', 'char', 'class', 'continue', 'debugger',
  85. 'default', 'delete', 'do', 'else', 'finally', 'for', 'function',
  86. 'if', 'in', 'instanceof', 'new', 'private', 'protected',
  87. 'public', 'return', 'static', 'switch', 'this', 'throw',
  88. 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield'];
  89. /* The symbol table ensures symbol unicity */
  90. symbolTable = {};
  91. st.symbolFor = function(string) {
  92. if(symbolTable[string] === undefined) {
  93. symbolTable[string] = new SmalltalkSymbol(string);
  94. };
  95. return symbolTable[string];
  96. };
  97. /* Unique ID number generator */
  98. oid = 0;
  99. st.nextId = function() {
  100. oid += 1;
  101. return oid;
  102. };
  103. /* We hold all Packages in a separate Object */
  104. st.packages = {};
  105. /* Smalltalk package creation. To add a Package, use smalltalk.addPackage() */
  106. function pkg(spec) {
  107. var that = new SmalltalkPackage();
  108. that.pkgName = spec.pkgName;
  109. that.organization = new SmalltalkOrganizer();
  110. that.properties = spec.properties || {};
  111. return that;
  112. };
  113. /* Smalltalk class creation. A class is an instance of an automatically
  114. created metaclass object. Newly created classes (not their metaclass)
  115. should be added to the smalltalk object, see smalltalk.addClass().
  116. Superclass linking is *not* handled here, see smalltalk.init() */
  117. function klass(spec) {
  118. var spec = spec || {};
  119. var meta = metaclass();
  120. var that = setupClass(meta.instanceClass, spec);
  121. that.className = spec.className;
  122. meta.className = spec.className + ' class';
  123. if(spec.superclass) {
  124. that.superclass = spec.superclass;
  125. meta.superclass = spec.superclass.klass;
  126. }
  127. return that;
  128. }
  129. function metaclass() {
  130. var meta = setupClass(new SmalltalkMetaclass(), {})
  131. meta.instanceClass = new meta.fn;
  132. return meta;
  133. }
  134. function setupClass(that, spec) {
  135. that.fn = spec.fn || function(){};
  136. that.iVarNames = spec.iVarNames || [];
  137. Object.defineProperty(that, "toString", {
  138. value: function() { return 'Smalltalk ' + this.className; },
  139. configurable: true // no writable - in par with ES6 methods
  140. });
  141. that.organization = new SmalltalkOrganizer();
  142. that.pkg = spec.pkg;
  143. Object.defineProperties(that.fn.prototype, {
  144. methods: { value: {}, enumerable: false, configurable: true, writable: true },
  145. inheritedMethods: { value: {}, enumerable: false, configurable: true, writable: true },
  146. klass: { value: that, enumerable: false, configurable: true, writable: true }
  147. });
  148. return that;
  149. };
  150. /* Smalltalk method object. To add a method to a class,
  151. use smalltalk.addMethod() */
  152. st.method = function(spec) {
  153. var that = new SmalltalkMethod();
  154. that.selector = spec.selector;
  155. that.jsSelector = spec.jsSelector;
  156. that.args = spec.args || {};
  157. that.category = spec.category;
  158. that.source = spec.source;
  159. that.messageSends = spec.messageSends || [];
  160. that.referencedClasses = spec.referencedClasses || [];
  161. that.fn = spec.fn;
  162. return that;
  163. };
  164. /* Initialize a class in its class hierarchy. Handle both class and
  165. metaclasses. */
  166. st.init = function(klass) {
  167. st.initClass(klass);
  168. if(klass.klass && !klass.meta) {
  169. st.initClass(klass.klass);
  170. }
  171. };
  172. st.initClass = function(klass) {
  173. var subclasses = st.subclasses(klass);
  174. var methods, prototype = klass.fn.prototype;
  175. if(klass.superclass && klass.superclass !== nil) {
  176. methods = st.methods(klass.superclass);
  177. //Methods linking
  178. for(var keys = Object.keys(methods), i=0; i<keys.length; i++) {
  179. var key = keys[i];
  180. if(!prototype.methods[key]) {
  181. prototype.inheritedMethods[key] = methods[key];
  182. Object.defineProperty(prototype, methods[key].jsSelector, {
  183. value: methods[key].fn, configurable: true, writable: true
  184. });
  185. }
  186. }
  187. }
  188. for(var i=0; i<subclasses.length; i++) {
  189. st.initClass(subclasses[i]);
  190. }
  191. };
  192. /* Answer all registered Packages as Array */
  193. st.packages.all = function() {
  194. var packages = [];
  195. for(var i in st.packages) {
  196. if (!st.packages.hasOwnProperty(i) || typeof(st.packages[i]) === "function") continue;
  197. packages.push(st.packages[i]);
  198. }
  199. return packages
  200. };
  201. /* Answer all registered Smalltalk classes */
  202. st.classes = function() {
  203. var classes = [], names = Object.keys(st), l = names.length;
  204. for (var i=0; i<l; i++) {
  205. var name = names[i];
  206. if (name.search(/^[A-Z]/) !== -1) {
  207. classes.push(st[name]);
  208. }
  209. }
  210. return classes;
  211. };
  212. /* Answer all methods (included inherited ones) of klass. */
  213. st.methods = function(klass) {
  214. var methods = {};
  215. inheritedMethods = klass.fn.prototype.inheritedMethods;
  216. for(var i=0, keys=Object.keys(inheritedMethods); i<keys.length; i++) {
  217. methods[keys[i]] = inheritedMethods[keys[i]];
  218. }
  219. var inheritedMethods = klass.fn.prototype.methods;
  220. for(var i=0, keys=Object.keys(inheritedMethods); i<keys.length; i++) {
  221. methods[keys[i]] = inheritedMethods[keys[i]];
  222. }
  223. return methods;
  224. };
  225. /* Answer the direct subclasses of klass. */
  226. st.subclasses = function(klass) {
  227. var subclasses = [];
  228. var classes = st.classes();
  229. for(var i=0; i < classes.length; i++) {
  230. var c = classes[i];
  231. if(c.fn) {
  232. //Classes
  233. if(c.superclass === klass) {
  234. subclasses.push(c);
  235. }
  236. c = c.klass;
  237. //Metaclasses
  238. if(c && c.superclass === klass) {
  239. subclasses.push(c);
  240. }
  241. }
  242. }
  243. return subclasses;
  244. };
  245. /* Create a new class wrapping a JavaScript constructor, and add it to the
  246. global smalltalk object. Package is lazily created if it does not exist with given name. */
  247. st.wrapClassName = function(className, pkgName, fn, superclass) {
  248. var pkg = st.addPackage(pkgName);
  249. st[className] = klass({
  250. className: className,
  251. superclass: superclass,
  252. pkg: pkg,
  253. fn: fn
  254. });
  255. };
  256. /* Create an alias for an existing class */
  257. st.alias = function(klass, alias) {
  258. st[alias] = klass;
  259. }
  260. /* Add a package to the smalltalk.packages object, creating a new one if needed.
  261. If pkgName is null or empty we return nil, which is an allowed package for a class.
  262. If package already exists we still update the properties of it. */
  263. st.addPackage = function(pkgName, properties) {
  264. if(!pkgName) {return nil;}
  265. if(!(st.packages[pkgName])) {
  266. st.packages[pkgName] = pkg({
  267. pkgName: pkgName,
  268. properties: properties
  269. });
  270. } else {
  271. if(properties) {
  272. st.packages[pkgName].properties = properties;
  273. }
  274. }
  275. return st.packages[pkgName];
  276. };
  277. /* Add a class to the smalltalk object, creating a new one if needed.
  278. A Package is lazily created if it does not exist with given name. */
  279. st.addClass = function(className, superclass, iVarNames, pkgName) {
  280. var pkg = st.addPackage(pkgName);
  281. if(st[className]) {
  282. st[className].superclass = superclass;
  283. st[className].iVarNames = iVarNames;
  284. st[className].pkg = pkg || st[className].pkg;
  285. } else {
  286. st[className] = klass({
  287. className: className,
  288. superclass: superclass,
  289. pkg: pkg,
  290. iVarNames: iVarNames
  291. });
  292. }
  293. pkg.organization.addElement(st[className]);
  294. };
  295. st.removeClass = function(klass) {
  296. klass.pkg.organization.removeElement(klass);
  297. delete st[klass.className];
  298. };
  299. /* Add/remove a method to/from a class */
  300. st.addMethod = function(jsSelector, method, klass) {
  301. Object.defineProperty(klass.fn.prototype, jsSelector, {
  302. value: method.fn, configurable: true, writable: true
  303. });
  304. klass.fn.prototype.methods[method.selector] = method;
  305. method.methodClass = klass;
  306. method.jsSelector = jsSelector;
  307. klass.organization.addElement(method.category);
  308. };
  309. st.removeMethod = function(method) {
  310. var protocol = method.category;
  311. var shouldDeleteProtocol;
  312. var klass = method.methodClass;
  313. delete klass.fn.prototype[method.selector._asSelector()];
  314. delete klass.fn.prototype.methods[method.selector];
  315. for(var i=0; i<klass.fn.prototype.methods; i++) {
  316. if(klass.fn.prototype.methods[i].category == protocol) {
  317. shouldDeleteProtocol = true;
  318. };
  319. };
  320. if(shouldDeleteProtocol) {
  321. klass.organization.removeElement(protocol)
  322. };
  323. };
  324. /* Handles unhandled errors during message sends */
  325. st.send = function(receiver, selector, args, klass) {
  326. if(st.thisContext) {
  327. return withContextSend(receiver, selector, args, klass);
  328. } else {
  329. try {return withContextSend(receiver, selector, args, klass)}
  330. catch(error) {
  331. // Reset the context stack in any case
  332. st.thisContext = undefined;
  333. if(error.smalltalkError) {
  334. handleError(error);
  335. } else {
  336. throw(error);
  337. }
  338. }
  339. }
  340. };
  341. function withContextSend(receiver, selector, args, klass) {
  342. var call, method;
  343. if(receiver == null) {
  344. receiver = nil;
  345. }
  346. method = klass ? klass.fn.prototype[selector] : receiver.klass && receiver[selector];
  347. if(method) {
  348. var context = pushContext(receiver, selector, method, args);
  349. call = method.apply(receiver, args);
  350. popContext(context);
  351. return call;
  352. } else {
  353. return messageNotUnderstood(receiver, selector, args);
  354. }
  355. };
  356. /* Handles Smalltalk errors. Triggers the registered ErrorHandler
  357. (See the Smalltalk class ErrorHandler and its subclasses */
  358. function handleError(error) {
  359. if(!error.cc) {
  360. smalltalk.ErrorHandler._current()._handleError_(error);
  361. }
  362. };
  363. /* Handles #dnu: *and* JavaScript method calls.
  364. if the receiver has no klass, we consider it a JS object (outside of the
  365. Amber system). Else assume that the receiver understands #doesNotUnderstand: */
  366. function messageNotUnderstood(receiver, selector, args) {
  367. /* Handles JS method calls. */
  368. if(receiver.klass === undefined || receiver.allowJavaScriptCalls) {
  369. return callJavaScriptMethod(receiver, selector, args);
  370. }
  371. /* Handles not understood messages. Also see the Amber counter-part
  372. Object>>doesNotUnderstand: */
  373. return receiver._doesNotUnderstand_(
  374. st.Message._new()
  375. ._selector_(st.convertSelector(selector))
  376. ._arguments_(args)
  377. );
  378. };
  379. /* Call a method of a JS object, or answer a property if it exists.
  380. Else try wrapping a JSObjectProxy around the receiver.
  381. If the object property is a function, then call it, except if it starts with
  382. an uppercase character (we probably want to answer the function itself in this
  383. case and send it #new from Amber).
  384. Converts keyword-based selectors by using the first
  385. keyword only, but keeping all message arguments.
  386. Example:
  387. "self do: aBlock with: anObject" -> "self.do(aBlock, anObject)" */
  388. function callJavaScriptMethod(receiver, selector, args) {
  389. var jsSelector = selector._asJavaScriptSelector();
  390. var jsProperty = receiver[jsSelector];
  391. if(typeof jsProperty === "function" && !/^[A-Z]/.test(jsSelector)) {
  392. return jsProperty.apply(receiver, args);
  393. } else if(jsProperty !== undefined) {
  394. if(args[0]) {
  395. receiver[jsSelector] = args[0];
  396. return nil;
  397. } else {
  398. return jsProperty;
  399. }
  400. }
  401. return st.send(st.JSObjectProxy._on_(receiver), selector, args);
  402. };
  403. /* Reuse one old context stored in oldContext */
  404. st.oldContext = null;
  405. /* Handle thisContext pseudo variable */
  406. st.getThisContext = function() {
  407. if(st.thisContext) {
  408. return st.thisContext.copy();
  409. }
  410. };
  411. function pushContext(receiver, selector, method, temps) {
  412. var c = st.oldContext, tc = st.thisContext;
  413. if (!c) {
  414. return st.thisContext = new SmalltalkMethodContext(receiver, selector, method, temps, tc);
  415. }
  416. st.oldContext = null;
  417. c.homeContext = tc;
  418. c.pc = 1;
  419. c.receiver = receiver;
  420. c.selector = selector;
  421. c.method = method;
  422. c.temps = temps || {};
  423. return st.thisContext = c;
  424. };
  425. function popContext(context) {
  426. st.thisContext = context.homeContext;
  427. context.homeContext = undefined;
  428. st.oldContext = context;
  429. };
  430. /* Convert a string to a valid smalltalk selector.
  431. if you modify the following functions, also change String>>asSelector
  432. accordingly */
  433. st.convertSelector = function(selector) {
  434. if(selector.match(/__/)) {
  435. return convertBinarySelector(selector);
  436. } else {
  437. return convertKeywordSelector(selector);
  438. }
  439. };
  440. function convertKeywordSelector(selector) {
  441. return selector.replace(/^_/, '').replace(/_/g, ':');
  442. };
  443. function convertBinarySelector(selector) {
  444. return selector
  445. .replace(/^_/, '')
  446. .replace(/_plus/, '+')
  447. .replace(/_minus/, '-')
  448. .replace(/_star/, '*')
  449. .replace(/_slash/, '/')
  450. .replace(/_gt/, '>')
  451. .replace(/_lt/, '<')
  452. .replace(/_eq/, '=')
  453. .replace(/_comma/, ',')
  454. .replace(/_at/, '@')
  455. };
  456. /* Converts a JavaScript object to valid Smalltalk Object */
  457. st.readJSObject = function(js) {
  458. var object = js;
  459. var readObject = (js.constructor === Object);
  460. var readArray = (js.constructor === Array);
  461. if(readObject) {
  462. object = smalltalk.Dictionary._new();
  463. }
  464. for(var i in js) {
  465. if(readObject) {
  466. object._at_put_(i, st.readJSObject(js[i]));
  467. }
  468. if(readArray) {
  469. object[i] = st.readJSObject(js[i]);
  470. }
  471. }
  472. return object;
  473. };
  474. /* Boolean assertion */
  475. st.assert = function(boolean) {
  476. if ((undefined !== boolean) && (boolean.klass === smalltalk.Boolean)) {
  477. return boolean;
  478. } else {
  479. smalltalk.NonBooleanReceiver._new()._object_(boolean)._signal();
  480. }
  481. }
  482. };
  483. function SmalltalkMethodContext(receiver, selector, method, temps, home) {
  484. this.receiver = receiver;
  485. this.selector = selector;
  486. this.method = method;
  487. this.temps = temps || {};
  488. this.homeContext = home;
  489. };
  490. SmalltalkMethodContext.prototype.copy = function() {
  491. var home = this.homeContext;
  492. if(home) {home = home.copy()}
  493. return new SmalltalkMethodContext(
  494. this.receiver,
  495. this.selector,
  496. this.method,
  497. this.temps,
  498. home
  499. );
  500. };
  501. SmalltalkMethodContext.prototype.resume = function() {
  502. //Brutally set the receiver as thisContext, then re-enter the function
  503. smalltalk.thisContext = this;
  504. return this.method.apply(receiver, temps);
  505. };
  506. /* Global Smalltalk objects. */
  507. var nil = new SmalltalkNil();
  508. var smalltalk = new Smalltalk();
  509. if(this.jQuery) {
  510. this.jQuery.allowJavaScriptCalls = true;
  511. }
  512. /****************************************************************************************/
  513. /* Base classes wrapping. If you edit this part, do not forget to set the superclass of the
  514. object metaclass to Class after the definition of Object */
  515. smalltalk.wrapClassName("Object", "Kernel", SmalltalkObject);
  516. smalltalk.wrapClassName("Smalltalk", "Kernel", Smalltalk, smalltalk.Object);
  517. smalltalk.wrapClassName("Package", "Kernel", SmalltalkPackage, smalltalk.Object);
  518. smalltalk.wrapClassName("Behavior", "Kernel", SmalltalkBehavior, smalltalk.Object);
  519. smalltalk.wrapClassName("Class", "Kernel", SmalltalkClass, smalltalk.Behavior);
  520. smalltalk.wrapClassName("Metaclass", "Kernel", SmalltalkMetaclass, smalltalk.Behavior);
  521. smalltalk.wrapClassName("CompiledMethod", "Kernel", SmalltalkMethod, smalltalk.Object);
  522. smalltalk.wrapClassName("Organizer", "Kernel-Objects", SmalltalkOrganizer, smalltalk.Object);
  523. smalltalk.Object.klass.superclass = smalltalk.Class;
  524. smalltalk.wrapClassName("Number", "Kernel", Number, smalltalk.Object);
  525. smalltalk.wrapClassName("BlockClosure", "Kernel", Function, smalltalk.Object);
  526. smalltalk.wrapClassName("Boolean", "Kernel", Boolean, smalltalk.Object);
  527. smalltalk.wrapClassName("Date", "Kernel", Date, smalltalk.Object);
  528. smalltalk.wrapClassName("UndefinedObject", "Kernel", SmalltalkNil, smalltalk.Object);
  529. smalltalk.wrapClassName("Collection", "Kernel", null, smalltalk.Object);
  530. smalltalk.wrapClassName("SequenceableCollection", "Kernel", null, smalltalk.Collection);
  531. smalltalk.wrapClassName("CharacterArray", "Kernel", null, smalltalk.SequenceableCollection);
  532. smalltalk.wrapClassName("String", "Kernel", String, smalltalk.CharacterArray);
  533. smalltalk.wrapClassName("Symbol", "Kernel", SmalltalkSymbol, smalltalk.CharacterArray);
  534. smalltalk.wrapClassName("Array", "Kernel", Array, smalltalk.SequenceableCollection);
  535. smalltalk.wrapClassName("RegularExpression", "Kernel", RegExp, smalltalk.String);
  536. smalltalk.wrapClassName("Error", "Kernel", Error, smalltalk.Object);
  537. smalltalk.wrapClassName("MethodContext", "Kernel", SmalltalkMethodContext, smalltalk.Object);
  538. /* Alias definitions */
  539. smalltalk.alias(smalltalk.Array, "OrderedCollection");
  540. smalltalk.alias(smalltalk.Date, "Time");