1
0

boot.js 18 KB

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