boot.js 16 KB

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