1
0

boot.js 16 KB

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