kernel-fundamentals.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /* ====================================================================
  2. |
  3. | Amber Smalltalk
  4. | http://amber-lang.net
  5. |
  6. ======================================================================
  7. ======================================================================
  8. |
  9. | Copyright (c) 2010-2014
  10. | Nicolas Petton <petton.nicolas@gmail.com>
  11. |
  12. | Copyright (c) 2012-2017
  13. | The Amber team https://lolg.it/org/amber/members
  14. | Amber contributors (see /CONTRIBUTORS)
  15. |
  16. | Amber is released under the MIT license
  17. |
  18. | Permission is hereby granted, free of charge, to any person obtaining
  19. | a copy of this software and associated documentation files (the
  20. | 'Software'), to deal in the Software without restriction, including
  21. | without limitation the rights to use, copy, modify, merge, publish,
  22. | distribute, sublicense, and/or sell copies of the Software, and to
  23. | permit persons to whom the Software is furnished to do so, subject to
  24. | the following conditions:
  25. |
  26. | The above copyright notice and this permission notice shall be
  27. | included in all copies or substantial portions of the Software.
  28. |
  29. | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
  30. | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  31. | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  32. | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  33. | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  34. | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  35. | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  36. |
  37. ==================================================================== */
  38. //jshint eqnull:true
  39. define(['./compatibility' /* TODO remove */], function () {
  40. "use strict";
  41. function inherits (child, parent) {
  42. child.prototype = Object.create(parent.prototype, {
  43. constructor: {
  44. value: child,
  45. enumerable: false, configurable: true, writable: true
  46. }
  47. });
  48. return child;
  49. }
  50. function SmalltalkGlobalsBrik (brikz, st) {
  51. // jshint evil:true
  52. var jsGlobals = new Function("return this")();
  53. var globals = Object.create(jsGlobals);
  54. globals.SmalltalkSettings = {};
  55. this.globals = globals;
  56. }
  57. // TODO kernel announcer instead of st._eventFooHappened(...args)
  58. function RootBrik (brikz, st) {
  59. /* Smalltalk foundational objects */
  60. var coreFns = this.coreFns = {};
  61. /* SmalltalkRoot is the hidden root of the normal Amber hierarchy.
  62. All objects including `ProtoObject` inherit from SmalltalkRoot.
  63. Detached roots (eg. wrapped JS classes like Number or Date)
  64. do not directly inherit from SmalltalkRoot, but employ a workaround.*/
  65. function SmalltalkRoot () {
  66. }
  67. function SmalltalkProtoObject () {
  68. }
  69. function SmalltalkObject () {
  70. }
  71. coreFns.ProtoObject = inherits(SmalltalkProtoObject, SmalltalkRoot);
  72. coreFns.Object = inherits(SmalltalkObject, SmalltalkProtoObject);
  73. this.Root = SmalltalkRoot;
  74. this.Object = SmalltalkObject;
  75. }
  76. OrganizeBrik.deps = ["arraySet", "root"];
  77. function OrganizeBrik (brikz, st) {
  78. var SmalltalkObject = brikz.root.Object;
  79. var coreFns = brikz.root.coreFns;
  80. var addElement = brikz.arraySet.addElement;
  81. function SmalltalkOrganizer () {
  82. }
  83. function SmalltalkClassOrganizer () {
  84. this.elements = [];
  85. }
  86. coreFns.Organizer = inherits(SmalltalkOrganizer, SmalltalkObject);
  87. coreFns.ClassOrganizer = inherits(SmalltalkClassOrganizer, SmalltalkOrganizer);
  88. this.setupClassOrganization = function (traitOrBehavior) {
  89. traitOrBehavior.organization = new SmalltalkClassOrganizer();
  90. traitOrBehavior.organization.theClass = traitOrBehavior;
  91. };
  92. this.addOrganizationElement = function (owner, element) {
  93. addElement(owner.organization.elements, element);
  94. };
  95. }
  96. SelectorsBrik.deps = ["selectorConversion"];
  97. function SelectorsBrik (brikz, st) {
  98. var selectorSet = Object.create(null);
  99. var selectors = this.selectors = [];
  100. var selectorPairs = this.selectorPairs = [];
  101. this.registerSelector = function (stSelector) {
  102. if (selectorSet[stSelector]) return null;
  103. var jsSelector = st.st2js(stSelector);
  104. selectorSet[stSelector] = true;
  105. selectors.push(stSelector);
  106. var pair = {st: stSelector, js: jsSelector};
  107. selectorPairs.push(pair);
  108. return pair;
  109. };
  110. st.allSelectors = function () {
  111. return selectors;
  112. };
  113. }
  114. function PackagesBrik (brikz, st) {
  115. st.packages = {};
  116. /* Add a package load descriptor to the system */
  117. st.addPackage = function (pkgName, properties) {
  118. if (!pkgName) return null;
  119. return st.packages[pkgName] = {
  120. pkgName: pkgName,
  121. properties: properties
  122. };
  123. };
  124. }
  125. BehaviorsBrik.deps = ["root", "smalltalkGlobals", "arraySet"];
  126. function BehaviorsBrik (brikz, st) {
  127. var globals = brikz.smalltalkGlobals.globals;
  128. var addElement = brikz.arraySet.addElement;
  129. var removeElement = brikz.arraySet.removeElement;
  130. /* Smalltalk classes */
  131. var classes = [];
  132. this.buildTraitOrClass = function (pkgName, builder) {
  133. var traitOrClass = globals.hasOwnProperty(builder.className) && globals[builder.className];
  134. if (traitOrClass) {
  135. if (!traitOrClass.pkg) throw new Error("Updated trait or class must have package: " + traitOrClass.className);
  136. // if (traitOrClass.pkg.pkgName !== pkgName) throw new Error("Incompatible cross-package update of trait or class: " + traitOrClass.className);
  137. builder.updateExisting(traitOrClass);
  138. } else {
  139. traitOrClass = builder.make();
  140. traitOrClass.pkg = pkgName;
  141. addTraitOrClass(traitOrClass);
  142. }
  143. return traitOrClass;
  144. };
  145. function addTraitOrClass (traitOrClass) {
  146. globals[traitOrClass.className] = traitOrClass;
  147. addElement(classes, traitOrClass);
  148. traitOrClass.added();
  149. }
  150. function removeTraitOrClass (traitOrClass) {
  151. traitOrClass.removed();
  152. removeElement(classes, traitOrClass);
  153. delete globals[traitOrClass.className];
  154. }
  155. this.removeTraitOrClass = removeTraitOrClass;
  156. /* Create an alias for an existing class */
  157. st.alias = function (traitOrClass, alias) {
  158. globals[alias] = traitOrClass;
  159. };
  160. /* Answer all registered Smalltalk classes */
  161. //TODO: remove the function and make smalltalk.classes an array
  162. st.classes = this.classes = function () {
  163. return classes;
  164. };
  165. }
  166. MethodsBrik.deps = ["composition", "selectors", "root", "selectorConversion"];
  167. function MethodsBrik (brikz, st) {
  168. var registerSelector = brikz.selectors.registerSelector;
  169. var updateMethod = brikz.composition.updateMethod;
  170. var SmalltalkObject = brikz.root.Object;
  171. var coreFns = brikz.root.coreFns;
  172. function SmalltalkMethod () {
  173. }
  174. coreFns.CompiledMethod = inherits(SmalltalkMethod, SmalltalkObject);
  175. /* Smalltalk method object. To add a method to a class,
  176. use api.addMethod() */
  177. st.method = function (spec) {
  178. var that = new SmalltalkMethod();
  179. var selector = spec.selector;
  180. that.selector = selector;
  181. that.jsSelector = st.st2js(selector);
  182. that.args = spec.args || {};
  183. that.protocol = spec.protocol;
  184. that.source = spec.source;
  185. that.messageSends = spec.messageSends || [];
  186. that.referencedClasses = spec.referencedClasses || [];
  187. that.fn = spec.fn;
  188. return that;
  189. };
  190. /* Add/remove a method to/from a class */
  191. st.addMethod = function (method, traitOrBehavior) {
  192. if (method.methodClass != null) {
  193. throw new Error("addMethod: Method " + method.selector + " already bound to " + method.methodClass);
  194. }
  195. method.methodClass = traitOrBehavior;
  196. registerNewSelectors(method);
  197. traitOrBehavior.localMethods[method.selector] = method;
  198. updateMethod(method.selector, traitOrBehavior);
  199. };
  200. function registerNewSelectors (method) {
  201. var newSelectors = [];
  202. function selectorInUse (stSelector) {
  203. var pair = registerSelector(stSelector);
  204. if (pair) {
  205. newSelectors.push(pair);
  206. }
  207. }
  208. selectorInUse(method.selector);
  209. method.messageSends.forEach(selectorInUse);
  210. if (st._selectorsAdded) st._selectorsAdded(newSelectors);
  211. }
  212. st.removeMethod = function (method, traitOrBehavior) {
  213. if (traitOrBehavior.localMethods[method.selector] !== method) return;
  214. delete traitOrBehavior.localMethods[method.selector];
  215. updateMethod(method.selector, traitOrBehavior);
  216. };
  217. }
  218. MethodCompositionBrik.deps = ["organize"];
  219. function MethodCompositionBrik (brikz, st) {
  220. var setupClassOrganization = brikz.organize.setupClassOrganization;
  221. var addOrganizationElement = brikz.organize.addOrganizationElement;
  222. this.setupMethods = function (traitOrBehavior) {
  223. setupClassOrganization(traitOrBehavior);
  224. traitOrBehavior.traitComposition = [];
  225. traitOrBehavior.localMethods = Object.create(null);
  226. traitOrBehavior.methods = Object.create(null);
  227. };
  228. function addMethod (method, traitOrBehavior) {
  229. traitOrBehavior.methods[method.selector] = method;
  230. // During the bootstrap, #addCompiledMethod is not used.
  231. // Therefore we populate the organizer here too
  232. addOrganizationElement(traitOrBehavior, method.protocol);
  233. traitOrBehavior.methodAdded(method);
  234. }
  235. function removeMethod (method, traitOrBehavior) {
  236. delete traitOrBehavior.methods[method.selector];
  237. traitOrBehavior.methodRemoved(method);
  238. // Do *not* delete protocols from here.
  239. // This is handled by #removeCompiledMethod
  240. }
  241. function aliased (selector, method) {
  242. if (method.selector === selector) return method;
  243. var result = st.method({
  244. selector: selector,
  245. args: method.args,
  246. protocol: method.protocol,
  247. source: '"Aliased as ' + selector + '"\n' + method.source,
  248. messageSends: method.messageSends,
  249. referencesClasses: method.referencedClasses,
  250. fn: method.fn
  251. });
  252. result.methodClass = method.methodClass;
  253. return result;
  254. }
  255. function deleteKeysFrom (keys, obj) {
  256. keys.forEach(function (each) {
  257. delete obj[each];
  258. });
  259. }
  260. function fillTraitTransformation (traitTransformation, obj) {
  261. // assert(Object.getOwnProperties(obj).length === 0)
  262. var traitMethods = traitTransformation.trait.methods;
  263. Object.keys(traitMethods).forEach(function (selector) {
  264. obj[selector] = traitMethods[selector];
  265. });
  266. var traitAliases = traitTransformation.aliases;
  267. if (traitAliases) {
  268. Object.keys(traitAliases).forEach(function (aliasSelector) {
  269. var aliasedMethod = traitMethods[traitAliases[aliasSelector]];
  270. if (aliasedMethod) obj[aliasSelector] = aliased(aliasSelector, aliasedMethod);
  271. // else delete obj[aliasSelector]; // semantically correct; optimized away
  272. });
  273. }
  274. var traitExclusions = traitTransformation.exclusions;
  275. if (traitExclusions) {
  276. deleteKeysFrom(traitExclusions, obj);
  277. }
  278. return obj;
  279. }
  280. function buildCompositionChain (traitComposition) {
  281. return traitComposition.reduce(function (soFar, each) {
  282. return fillTraitTransformation(each, Object.create(soFar));
  283. }, null);
  284. }
  285. st.setTraitComposition = function (traitComposition, traitOrBehavior) {
  286. var oldLocalMethods = traitOrBehavior.localMethods,
  287. newLocalMethods = Object.create(buildCompositionChain(traitComposition));
  288. Object.keys(oldLocalMethods).forEach(function (selector) {
  289. newLocalMethods[selector] = oldLocalMethods[selector];
  290. });
  291. var selector;
  292. traitOrBehavior.localMethods = newLocalMethods;
  293. for (selector in newLocalMethods) {
  294. updateMethod(selector, traitOrBehavior);
  295. }
  296. for (selector in oldLocalMethods) {
  297. updateMethod(selector, traitOrBehavior);
  298. }
  299. traitOrBehavior.traitComposition.forEach(function (each) {
  300. each.trait.removeUser(traitOrBehavior);
  301. });
  302. traitOrBehavior.traitComposition = traitComposition;
  303. traitOrBehavior.traitComposition.forEach(function (each) {
  304. each.trait.addUser(traitOrBehavior);
  305. });
  306. };
  307. function updateMethod (selector, traitOrBehavior) {
  308. var oldMethod = traitOrBehavior.methods[selector],
  309. newMethod = traitOrBehavior.localMethods[selector];
  310. if (oldMethod == null && newMethod == null) {
  311. console.warn("Removal of nonexistent method " + traitOrBehavior + " >> " + selector);
  312. return;
  313. }
  314. if (newMethod === oldMethod) return;
  315. if (newMethod != null) addMethod(newMethod, traitOrBehavior);
  316. else removeMethod(oldMethod, traitOrBehavior);
  317. }
  318. this.updateMethod = updateMethod;
  319. function aliasesOfSelector (selector, traitAliases) {
  320. if (!traitAliases) return [selector];
  321. var result = Object.keys(traitAliases).filter(function (aliasSelector) {
  322. return traitAliases[aliasSelector] === selector
  323. });
  324. if (!traitAliases[selector]) result.push(selector);
  325. return result;
  326. }
  327. function applyTraitMethodAddition (selector, method, traitTransformation, obj) {
  328. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  329. changes.forEach(function (aliasSelector) {
  330. obj[aliasSelector] = aliased(aliasSelector, method);
  331. });
  332. var traitExclusions = traitTransformation.exclusions;
  333. if (traitExclusions) {
  334. deleteKeysFrom(traitExclusions, obj);
  335. }
  336. return changes;
  337. }
  338. function applyTraitMethodDeletion (selector, traitTransformation, obj) {
  339. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  340. deleteKeysFrom(changes, obj);
  341. return changes;
  342. }
  343. function traitMethodChanged (selector, method, trait, traitOrBehavior) {
  344. var traitComposition = traitOrBehavior.traitComposition,
  345. chain = traitOrBehavior.localMethods,
  346. changes = [];
  347. for (var i = traitComposition.length - 1; i >= 0; --i) {
  348. chain = Object.getPrototypeOf(chain);
  349. var traitTransformation = traitComposition[i];
  350. if (traitTransformation.trait !== trait) continue;
  351. changes.push.apply(changes, method ?
  352. applyTraitMethodAddition(selector, method, traitTransformation, chain) :
  353. applyTraitMethodDeletion(selector, traitTransformation, chain));
  354. }
  355. // assert(chain === null);
  356. changes.forEach(function (each) {
  357. updateMethod(each, traitOrBehavior);
  358. });
  359. }
  360. this.traitMethodChanged = traitMethodChanged;
  361. }
  362. function ArraySetBrik (brikz, st) {
  363. st.addElement = this.addElement = function (array, el) {
  364. if (typeof el === 'undefined') {
  365. return;
  366. }
  367. if (array.indexOf(el) === -1) {
  368. array.push(el);
  369. }
  370. };
  371. st.removeElement = this.removeElement = function (array, el) {
  372. var i = array.indexOf(el);
  373. if (i !== -1) {
  374. array.splice(i, 1);
  375. }
  376. };
  377. }
  378. function SelectorConversionBrik (brikz, st) {
  379. /* Convert a Smalltalk selector into a JS selector */
  380. st.st2js = function (string) {
  381. return '_' + string
  382. .replace(/:/g, '_')
  383. .replace(/[\&]/g, '_and')
  384. .replace(/[\|]/g, '_or')
  385. .replace(/[+]/g, '_plus')
  386. .replace(/-/g, '_minus')
  387. .replace(/[*]/g, '_star')
  388. .replace(/[\/]/g, '_slash')
  389. .replace(/[\\]/g, '_backslash')
  390. .replace(/[\~]/g, '_tild')
  391. .replace(/%/g, '_percent')
  392. .replace(/>/g, '_gt')
  393. .replace(/</g, '_lt')
  394. .replace(/=/g, '_eq')
  395. .replace(/,/g, '_comma')
  396. .replace(/[@]/g, '_at');
  397. };
  398. /* Convert a string to a valid smalltalk selector.
  399. if you modify the following functions, also change st2js
  400. accordingly */
  401. st.js2st = function (selector) {
  402. if (selector.match(/^__/)) {
  403. return binaryJsToSt(selector);
  404. } else {
  405. return keywordJsToSt(selector);
  406. }
  407. };
  408. function keywordJsToSt (selector) {
  409. return selector.replace(/^_/, '').replace(/_/g, ':');
  410. }
  411. function binaryJsToSt (selector) {
  412. return selector
  413. .replace(/^_/, '')
  414. .replace(/_and/g, '&')
  415. .replace(/_or/g, '|')
  416. .replace(/_plus/g, '+')
  417. .replace(/_minus/g, '-')
  418. .replace(/_star/g, '*')
  419. .replace(/_slash/g, '/')
  420. .replace(/_backslash/g, '\\')
  421. .replace(/_tild/g, '~')
  422. .replace(/_percent/g, '%')
  423. .replace(/_gt/g, '>')
  424. .replace(/_lt/g, '<')
  425. .replace(/_eq/g, '=')
  426. .replace(/_comma/g, ',')
  427. .replace(/_at/g, '@');
  428. }
  429. st.st2prop = function (stSelector) {
  430. var colonPosition = stSelector.indexOf(':');
  431. return colonPosition === -1 ? stSelector : stSelector.slice(0, colonPosition);
  432. };
  433. }
  434. /* Making smalltalk that has basic building blocks */
  435. function configureWithFundamentals (brikz) {
  436. brikz.smalltalkGlobals = SmalltalkGlobalsBrik;
  437. brikz.root = RootBrik;
  438. brikz.arraySet = ArraySetBrik;
  439. brikz.organize = OrganizeBrik;
  440. brikz.selectorConversion = SelectorConversionBrik;
  441. brikz.selectors = SelectorsBrik;
  442. brikz.packages = PackagesBrik;
  443. brikz.composition = MethodCompositionBrik;
  444. brikz.behaviors = BehaviorsBrik;
  445. brikz.methods = MethodsBrik;
  446. brikz.rebuild();
  447. }
  448. return configureWithFundamentals;
  449. });