2
0

boot.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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.initClass(klass);
  147. if(klass.klass && !klass.meta) {
  148. st.initClass(klass.klass);
  149. }
  150. };
  151. st.initClass = function(klass) {
  152. var subclasses = st.subclasses(klass);
  153. var methods, prototype = 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; i<keys.length; i++) {
  158. var key = keys[i];
  159. if(!prototype.methods[key]) {
  160. prototype.inheritedMethods[key] = methods[key];
  161. Object.defineProperty(prototype, methods[key].jsSelector, {
  162. value: methods[key].fn, configurable: true, writable: true
  163. });
  164. }
  165. }
  166. }
  167. for(var i=0; i<subclasses.length; i++) {
  168. st.initClass(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. inheritedMethods = klass.fn.prototype.inheritedMethods;
  195. for(var i=0, keys=Object.keys(inheritedMethods); i<keys.length; i++) {
  196. methods[keys[i]] = inheritedMethods[keys[i]];
  197. }
  198. var inheritedMethods = klass.fn.prototype.methods;
  199. for(var i=0, keys=Object.keys(inheritedMethods); i<keys.length; i++) {
  200. methods[keys[i]] = inheritedMethods[keys[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; i < classes.length; 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. A 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, writable: true
  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, method;
  301. if(receiver == null) {
  302. receiver = nil;
  303. }
  304. method = klass ? klass.fn.prototype[selector] : receiver.klass && receiver[selector];
  305. if(method) {
  306. var context = pushContext(receiver, selector, method, args);
  307. call = method.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. if(!error.cc) {
  318. smalltalk.ErrorHandler._current()._handleError_(error);
  319. }
  320. };
  321. /* Handles #dnu: *and* JavaScript method calls.
  322. if the receiver has no klass, we consider it a JS object (outside of the
  323. Amber system). Else assume that the receiver understands #doesNotUnderstand: */
  324. function messageNotUnderstood(receiver, selector, args) {
  325. /* Handles JS method calls. */
  326. if(receiver.klass === undefined || receiver.allowJavaScriptCalls) {
  327. return callJavaScriptMethod(receiver, selector, args);
  328. }
  329. /* Handles not understood messages. Also see the Amber counter-part
  330. Object>>doesNotUnderstand: */
  331. return receiver._doesNotUnderstand_(
  332. st.Message._new()
  333. ._selector_(st.convertSelector(selector))
  334. ._arguments_(args)
  335. );
  336. };
  337. /* Call a method of a JS object, or answer a property if it exists.
  338. Else try wrapping a JSObjectProxy around the receiver.
  339. If the object property is a function, then call it, except if it starts with
  340. an uppercase character (we probably want to answer the function itself in this
  341. case and send it #new from Amber).
  342. Converts keyword-based selectors by using the first
  343. keyword only, but keeping all message arguments.
  344. Example:
  345. "self do: aBlock with: anObject" -> "self.do(aBlock, anObject)" */
  346. function callJavaScriptMethod(receiver, selector, args) {
  347. var jsSelector = selector._asJavaScriptSelector();
  348. var jsProperty = receiver[jsSelector];
  349. if(typeof jsProperty === "function" && !/^[A-Z]/.test(jsSelector)) {
  350. return jsProperty.apply(receiver, args);
  351. } else if(jsProperty !== undefined) {
  352. if(args[0]) {
  353. receiver[jsSelector] = args[0];
  354. return nil;
  355. } else {
  356. return jsProperty;
  357. }
  358. }
  359. return st.send(st.JSObjectProxy._on_(receiver), selector, args);
  360. };
  361. /* Reuse one old context stored in oldContext */
  362. st.oldContext = null;
  363. /* Handle thisContext pseudo variable */
  364. st.getThisContext = function() {
  365. if(st.thisContext) {
  366. return st.thisContext.copy();
  367. }
  368. };
  369. function pushContext(receiver, selector, method, temps) {
  370. var c = st.oldContext, tc = st.thisContext;
  371. if (!c) {
  372. return st.thisContext = new SmalltalkMethodContext(receiver, selector, method, temps, tc);
  373. }
  374. st.oldContext = null;
  375. c.homeContext = tc;
  376. c.pc = 1;
  377. c.receiver = receiver;
  378. c.selector = selector;
  379. c.method = method;
  380. c.temps = temps || {};
  381. return st.thisContext = c;
  382. };
  383. function popContext(context) {
  384. st.thisContext = context.homeContext;
  385. context.homeContext = undefined;
  386. st.oldContext = context;
  387. };
  388. /* Convert a string to a valid smalltalk selector.
  389. if you modify the following functions, also change String>>asSelector
  390. accordingly */
  391. st.convertSelector = function(selector) {
  392. if(selector.match(/__/)) {
  393. return convertBinarySelector(selector);
  394. } else {
  395. return convertKeywordSelector(selector);
  396. }
  397. };
  398. function convertKeywordSelector(selector) {
  399. return selector.replace(/^_/, '').replace(/_/g, ':');
  400. };
  401. function convertBinarySelector(selector) {
  402. return selector
  403. .replace(/^_/, '')
  404. .replace(/_plus/, '+')
  405. .replace(/_minus/, '-')
  406. .replace(/_star/, '*')
  407. .replace(/_slash/, '/')
  408. .replace(/_gt/, '>')
  409. .replace(/_lt/, '<')
  410. .replace(/_eq/, '=')
  411. .replace(/_comma/, ',')
  412. .replace(/_at/, '@')
  413. };
  414. /* Converts a JavaScript object to valid Smalltalk Object */
  415. st.readJSObject = function(js) {
  416. var object = js;
  417. var readObject = (js.constructor === Object);
  418. var readArray = (js.constructor === Array);
  419. if(readObject) {
  420. object = smalltalk.Dictionary._new();
  421. }
  422. for(var i in js) {
  423. if(readObject) {
  424. object._at_put_(i, st.readJSObject(js[i]));
  425. }
  426. if(readArray) {
  427. object[i] = st.readJSObject(js[i]);
  428. }
  429. }
  430. return object;
  431. };
  432. /* Boolean assertion */
  433. st.assert = function(boolean) {
  434. if(boolean.klass === smalltalk.Boolean) {
  435. return boolean;
  436. } else {
  437. smalltalk.NonBooleanReceiver._new()._object_(boolean)._signal();
  438. }
  439. }
  440. };
  441. function SmalltalkMethodContext(receiver, selector, method, temps, home) {
  442. this.receiver = receiver;
  443. this.selector = selector;
  444. this.method = method;
  445. this.temps = temps || {};
  446. this.homeContext = home;
  447. this.resume = function() {
  448. //Brutally set the receiver as thisContext, then re-enter the function
  449. smalltalk.thisContext = this;
  450. return this.method.apply(receiver, temps);
  451. };
  452. };
  453. SmalltalkMethodContext.prototype.copy = function() {
  454. var home = this.homeContext;
  455. if(home) {home = home.copy()}
  456. return new SmalltalkMethodContext(
  457. this.receiver,
  458. this.selector,
  459. this.method,
  460. this.temps,
  461. home
  462. );
  463. };
  464. /* Global Smalltalk objects. */
  465. var nil = new SmalltalkNil();
  466. var smalltalk = new Smalltalk();
  467. if(this.jQuery) {
  468. this.jQuery.allowJavaScriptCalls = true;
  469. }
  470. /****************************************************************************************/
  471. /* Base classes wrapping. If you edit this part, do not forget to set the superclass of the
  472. object metaclass to Class after the definition of Object */
  473. smalltalk.wrapClassName("Object", "Kernel", SmalltalkObject);
  474. smalltalk.wrapClassName("Smalltalk", "Kernel", Smalltalk, smalltalk.Object);
  475. smalltalk.wrapClassName("Package", "Kernel", SmalltalkPackage, smalltalk.Object);
  476. smalltalk.wrapClassName("Behavior", "Kernel", SmalltalkBehavior, smalltalk.Object);
  477. smalltalk.wrapClassName("Class", "Kernel", SmalltalkClass, smalltalk.Behavior);
  478. smalltalk.wrapClassName("Metaclass", "Kernel", SmalltalkMetaclass, smalltalk.Behavior);
  479. smalltalk.wrapClassName("CompiledMethod", "Kernel", SmalltalkMethod, smalltalk.Object);
  480. smalltalk.Object.klass.superclass = smalltalk.Class;
  481. smalltalk.wrapClassName("Number", "Kernel", Number, smalltalk.Object);
  482. smalltalk.wrapClassName("BlockClosure", "Kernel", Function, smalltalk.Object);
  483. smalltalk.wrapClassName("Boolean", "Kernel", Boolean, smalltalk.Object);
  484. smalltalk.wrapClassName("Date", "Kernel", Date, smalltalk.Object);
  485. smalltalk.wrapClassName("UndefinedObject", "Kernel", SmalltalkNil, smalltalk.Object);
  486. smalltalk.wrapClassName("Collection", "Kernel", null, smalltalk.Object);
  487. smalltalk.wrapClassName("SequenceableCollection", "Kernel", null, smalltalk.Collection);
  488. smalltalk.wrapClassName("CharacterArray", "Kernel", null, smalltalk.SequenceableCollection);
  489. smalltalk.wrapClassName("String", "Kernel", String, smalltalk.CharacterArray);
  490. smalltalk.wrapClassName("Symbol", "Kernel", SmalltalkSymbol, smalltalk.CharacterArray);
  491. smalltalk.wrapClassName("Array", "Kernel", Array, smalltalk.SequenceableCollection);
  492. smalltalk.wrapClassName("RegularExpression", "Kernel", RegExp, smalltalk.String);
  493. smalltalk.wrapClassName("Error", "Kernel", Error, smalltalk.Object);
  494. smalltalk.wrapClassName("MethodContext", "Kernel", SmalltalkMethodContext, smalltalk.Object);
  495. /* Alias definitions */
  496. smalltalk.alias(smalltalk.Array, "OrderedCollection");
  497. smalltalk.alias(smalltalk.Date, "Time");