boot.js 19 KB

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