2
0

boot.js 17 KB

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