kernel-fundamentals.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. function RootBrik (brikz, st) {
  58. /* Smalltalk foundational objects */
  59. var coreFns = this.coreFns = {};
  60. /* SmalltalkRoot is the hidden root of the normal Amber hierarchy.
  61. All objects including `ProtoObject` inherit from SmalltalkRoot.
  62. Detached roots (eg. wrapped JS classes like Number or Date)
  63. do not directly inherit from SmalltalkRoot, but employ a workaround.*/
  64. function SmalltalkRoot () {
  65. }
  66. function SmalltalkProtoObject () {
  67. }
  68. function SmalltalkObject () {
  69. }
  70. coreFns.ProtoObject = inherits(SmalltalkProtoObject, SmalltalkRoot);
  71. coreFns.Object = inherits(SmalltalkObject, SmalltalkProtoObject);
  72. this.Root = SmalltalkRoot;
  73. this.Object = SmalltalkObject;
  74. }
  75. OrganizeBrik.deps = ["arraySet", "root"];
  76. function OrganizeBrik (brikz, st) {
  77. var SmalltalkObject = brikz.root.Object;
  78. var coreFns = brikz.root.coreFns;
  79. var addElement = brikz.arraySet.addElement;
  80. function SmalltalkOrganizer () {
  81. }
  82. function SmalltalkClassOrganizer () {
  83. this.elements = [];
  84. }
  85. coreFns.Organizer = inherits(SmalltalkOrganizer, SmalltalkObject);
  86. coreFns.ClassOrganizer = inherits(SmalltalkClassOrganizer, SmalltalkOrganizer);
  87. this.setupClassOrganization = function (traitOrBehavior) {
  88. traitOrBehavior.organization = new SmalltalkClassOrganizer();
  89. traitOrBehavior.organization.theClass = traitOrBehavior;
  90. };
  91. this.addOrganizationElement = function (owner, element) {
  92. addElement(owner.organization.elements, element);
  93. };
  94. }
  95. SelectorsBrik.deps = ["selectorConversion"];
  96. function SelectorsBrik (brikz, st) {
  97. var selectorSet = Object.create(null);
  98. var selectors = this.selectors = [];
  99. var selectorPairs = this.selectorPairs = [];
  100. this.registerSelector = function (stSelector) {
  101. if (selectorSet[stSelector]) return null;
  102. var jsSelector = st.st2js(stSelector);
  103. selectorSet[stSelector] = true;
  104. selectors.push(stSelector);
  105. var pair = {st: stSelector, js: jsSelector};
  106. selectorPairs.push(pair);
  107. return pair;
  108. };
  109. st.allSelectors = function () {
  110. return selectors;
  111. };
  112. }
  113. function PackagesBrik (brikz, st) {
  114. st.packages = {};
  115. /* Add a package load descriptor to the system */
  116. st.addPackage = function (pkgName, properties) {
  117. if (!pkgName) return null;
  118. return st.packages[pkgName] = {
  119. pkgName: pkgName,
  120. properties: properties
  121. };
  122. };
  123. }
  124. BehaviorsBrik.deps = ["root", "smalltalkGlobals", "arraySet"];
  125. function BehaviorsBrik (brikz, st) {
  126. var globals = brikz.smalltalkGlobals.globals;
  127. var addElement = brikz.arraySet.addElement;
  128. var removeElement = brikz.arraySet.removeElement;
  129. /* Smalltalk classes */
  130. var classes = [];
  131. this.buildTraitOrClass = function (pkgName, builder) {
  132. var traitOrClass = globals.hasOwnProperty(builder.className) && globals[builder.className];
  133. if (traitOrClass) {
  134. if (!traitOrClass.pkg) throw new Error("Updated trait or class must have package: " + traitOrClass.className);
  135. if (traitOrClass.pkg.pkgName !== pkgName) throw new Error("Incompatible cross-package update of trait or class: " + traitOrClass.className);
  136. builder.updateExisting(traitOrClass);
  137. } else {
  138. traitOrClass = builder.make();
  139. traitOrClass.pkg = pkgName;
  140. addTraitOrClass(traitOrClass);
  141. }
  142. return traitOrClass;
  143. };
  144. function addTraitOrClass (traitOrClass) {
  145. globals[traitOrClass.className] = traitOrClass;
  146. addElement(classes, traitOrClass);
  147. traitOrClass.added();
  148. }
  149. function removeTraitOrClass (traitOrClass) {
  150. traitOrClass.removed();
  151. removeElement(classes, traitOrClass);
  152. delete globals[traitOrClass.className];
  153. }
  154. this.removeTraitOrClass = removeTraitOrClass;
  155. /* Create an alias for an existing class */
  156. st.alias = function (traitOrClass, alias) {
  157. globals[alias] = traitOrClass;
  158. };
  159. /* Answer all registered Smalltalk classes */
  160. //TODO: remove the function and make smalltalk.classes an array
  161. st.classes = this.classes = function () {
  162. return classes;
  163. };
  164. }
  165. MethodsBrik.deps = ["composition", "selectors", "root", "selectorConversion"];
  166. function MethodsBrik (brikz, st) {
  167. var registerSelector = brikz.selectors.registerSelector;
  168. var updateMethod = brikz.composition.updateMethod;
  169. var SmalltalkObject = brikz.root.Object;
  170. var coreFns = brikz.root.coreFns;
  171. function SmalltalkMethod () {
  172. }
  173. coreFns.CompiledMethod = inherits(SmalltalkMethod, SmalltalkObject);
  174. /* Smalltalk method object. To add a method to a class,
  175. use api.addMethod() */
  176. st.method = function (spec) {
  177. var that = new SmalltalkMethod();
  178. var selector = spec.selector;
  179. that.selector = selector;
  180. that.jsSelector = st.st2js(selector);
  181. that.args = spec.args || {};
  182. that.protocol = spec.protocol;
  183. that.source = spec.source;
  184. that.messageSends = spec.messageSends || [];
  185. that.referencedClasses = spec.referencedClasses || [];
  186. that.fn = spec.fn;
  187. return that;
  188. };
  189. /* Add/remove a method to/from a class */
  190. st.addMethod = function (method, traitOrBehavior) {
  191. if (method.methodClass != null) {
  192. throw new Error("addMethod: Method " + method.selector + " already bound to " + method.methodClass);
  193. }
  194. method.methodClass = traitOrBehavior;
  195. registerNewSelectors(method);
  196. traitOrBehavior.localMethods[method.selector] = method;
  197. updateMethod(method.selector, traitOrBehavior);
  198. };
  199. function registerNewSelectors (method) {
  200. var newSelectors = [];
  201. function selectorInUse (stSelector) {
  202. var pair = registerSelector(stSelector);
  203. if (pair) {
  204. newSelectors.push(pair);
  205. }
  206. }
  207. selectorInUse(method.selector);
  208. method.messageSends.forEach(selectorInUse);
  209. if (st._selectorsAdded) st._selectorsAdded(newSelectors);
  210. }
  211. st.removeMethod = function (method, traitOrBehavior) {
  212. if (traitOrBehavior.localMethods[method.selector] !== method) return;
  213. delete traitOrBehavior.localMethods[method.selector];
  214. updateMethod(method.selector, traitOrBehavior);
  215. };
  216. }
  217. MethodCompositionBrik.deps = ["organize"];
  218. function MethodCompositionBrik (brikz, st) {
  219. var setupClassOrganization = brikz.organize.setupClassOrganization;
  220. var addOrganizationElement = brikz.organize.addOrganizationElement;
  221. this.setupMethods = function (traitOrBehavior) {
  222. setupClassOrganization(traitOrBehavior);
  223. traitOrBehavior.traitComposition = [];
  224. traitOrBehavior.localMethods = Object.create(null);
  225. traitOrBehavior.methods = Object.create(null);
  226. };
  227. function addMethod (method, traitOrBehavior) {
  228. traitOrBehavior.methods[method.selector] = method;
  229. // During the bootstrap, #addCompiledMethod is not used.
  230. // Therefore we populate the organizer here too
  231. addOrganizationElement(traitOrBehavior, method.protocol);
  232. traitOrBehavior.methodAdded(method);
  233. }
  234. function removeMethod (method, traitOrBehavior) {
  235. delete traitOrBehavior.methods[method.selector];
  236. traitOrBehavior.methodRemoved(method);
  237. // Do *not* delete protocols from here.
  238. // This is handled by #removeCompiledMethod
  239. }
  240. function aliased (selector, method) {
  241. if (method.selector === selector) return method;
  242. var result = st.method({
  243. selector: selector,
  244. args: method.args,
  245. protocol: method.protocol,
  246. source: '"Aliased as ' + selector + '"\n' + method.source,
  247. messageSends: method.messageSends,
  248. referencesClasses: method.referencedClasses,
  249. fn: method.fn
  250. });
  251. result.methodClass = method.methodClass;
  252. return result;
  253. }
  254. function deleteKeysFrom (keys, obj) {
  255. keys.forEach(function (each) {
  256. delete obj[each];
  257. });
  258. }
  259. function fillTraitTransformation (traitTransformation, obj) {
  260. // assert(Object.getOwnProperties(obj).length === 0)
  261. var traitMethods = traitTransformation.trait.methods;
  262. Object.keys(traitMethods).forEach(function (selector) {
  263. obj[selector] = traitMethods[selector];
  264. });
  265. var traitAliases = traitTransformation.aliases;
  266. if (traitAliases) {
  267. Object.keys(traitAliases).forEach(function (aliasSelector) {
  268. var aliasedMethod = traitMethods[traitAliases[aliasSelector]];
  269. if (aliasedMethod) obj[aliasSelector] = aliased(aliasSelector, aliasedMethod);
  270. // else delete obj[aliasSelector]; // semantically correct; optimized away
  271. });
  272. }
  273. var traitExclusions = traitTransformation.exclusions;
  274. if (traitExclusions) {
  275. deleteKeysFrom(traitExclusions, obj);
  276. }
  277. return obj;
  278. }
  279. function buildCompositionChain (traitComposition) {
  280. return traitComposition.reduce(function (soFar, each) {
  281. return fillTraitTransformation(each, Object.create(soFar));
  282. }, null);
  283. }
  284. st.setTraitComposition = function (traitComposition, traitOrBehavior) {
  285. var oldLocalMethods = traitOrBehavior.localMethods,
  286. newLocalMethods = Object.create(buildCompositionChain(traitComposition));
  287. Object.keys(oldLocalMethods).forEach(function (selector) {
  288. newLocalMethods[selector] = oldLocalMethods[selector];
  289. });
  290. var selector;
  291. traitOrBehavior.localMethods = newLocalMethods;
  292. for (selector in newLocalMethods) {
  293. updateMethod(selector, traitOrBehavior);
  294. }
  295. for (selector in oldLocalMethods) {
  296. updateMethod(selector, traitOrBehavior);
  297. }
  298. traitOrBehavior.traitComposition.forEach(function (each) {
  299. each.trait.removeUser(traitOrBehavior);
  300. });
  301. traitOrBehavior.traitComposition = traitComposition;
  302. traitOrBehavior.traitComposition.forEach(function (each) {
  303. each.trait.addUser(traitOrBehavior);
  304. });
  305. };
  306. function updateMethod (selector, traitOrBehavior) {
  307. var oldMethod = traitOrBehavior.methods[selector],
  308. newMethod = traitOrBehavior.localMethods[selector];
  309. if (oldMethod == null && newMethod == null) {
  310. console.warn("Removal of nonexistent method " + traitOrBehavior + " >> " + selector);
  311. return;
  312. }
  313. if (newMethod === oldMethod) return;
  314. if (newMethod != null) addMethod(newMethod, traitOrBehavior);
  315. else removeMethod(oldMethod, traitOrBehavior);
  316. }
  317. this.updateMethod = updateMethod;
  318. function aliasesOfSelector (selector, traitAliases) {
  319. if (!traitAliases) return [selector];
  320. var result = Object.keys(traitAliases).filter(function (aliasSelector) {
  321. return traitAliases[aliasSelector] === selector
  322. });
  323. if (!traitAliases[selector]) result.push(selector);
  324. return result;
  325. }
  326. function applyTraitMethodAddition (selector, method, traitTransformation, obj) {
  327. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  328. changes.forEach(function (aliasSelector) {
  329. obj[aliasSelector] = aliased(aliasSelector, method);
  330. });
  331. var traitExclusions = traitTransformation.exclusions;
  332. if (traitExclusions) {
  333. deleteKeysFrom(traitExclusions, obj);
  334. }
  335. return changes;
  336. }
  337. function applyTraitMethodDeletion (selector, traitTransformation, obj) {
  338. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  339. deleteKeysFrom(changes, obj);
  340. return changes;
  341. }
  342. function traitMethodChanged (selector, method, trait, traitOrBehavior) {
  343. var traitComposition = traitOrBehavior.traitComposition,
  344. chain = traitOrBehavior.localMethods,
  345. changes = [];
  346. for (var i = traitComposition.length - 1; i >= 0; --i) {
  347. chain = Object.getPrototypeOf(chain);
  348. var traitTransformation = traitComposition[i];
  349. if (traitTransformation.trait !== trait) continue;
  350. changes.push.apply(changes, method ?
  351. applyTraitMethodAddition(selector, method, traitTransformation, chain) :
  352. applyTraitMethodDeletion(selector, traitTransformation, chain));
  353. }
  354. // assert(chain === null);
  355. changes.forEach(function (each) {
  356. updateMethod(each, traitOrBehavior);
  357. });
  358. }
  359. this.traitMethodChanged = traitMethodChanged;
  360. }
  361. function ArraySetBrik (brikz, st) {
  362. st.addElement = this.addElement = function (array, el) {
  363. if (typeof el === 'undefined') {
  364. return;
  365. }
  366. if (array.indexOf(el) === -1) {
  367. array.push(el);
  368. }
  369. };
  370. st.removeElement = this.removeElement = function (array, el) {
  371. var i = array.indexOf(el);
  372. if (i !== -1) {
  373. array.splice(i, 1);
  374. }
  375. };
  376. }
  377. function SelectorConversionBrik (brikz, st) {
  378. /* Convert a Smalltalk selector into a JS selector */
  379. st.st2js = function (string) {
  380. return '_' + string
  381. .replace(/:/g, '_')
  382. .replace(/[\&]/g, '_and')
  383. .replace(/[\|]/g, '_or')
  384. .replace(/[+]/g, '_plus')
  385. .replace(/-/g, '_minus')
  386. .replace(/[*]/g, '_star')
  387. .replace(/[\/]/g, '_slash')
  388. .replace(/[\\]/g, '_backslash')
  389. .replace(/[\~]/g, '_tild')
  390. .replace(/%/g, '_percent')
  391. .replace(/>/g, '_gt')
  392. .replace(/</g, '_lt')
  393. .replace(/=/g, '_eq')
  394. .replace(/,/g, '_comma')
  395. .replace(/[@]/g, '_at');
  396. };
  397. /* Convert a string to a valid smalltalk selector.
  398. if you modify the following functions, also change st2js
  399. accordingly */
  400. st.js2st = function (selector) {
  401. if (selector.match(/^__/)) {
  402. return binaryJsToSt(selector);
  403. } else {
  404. return keywordJsToSt(selector);
  405. }
  406. };
  407. function keywordJsToSt (selector) {
  408. return selector.replace(/^_/, '').replace(/_/g, ':');
  409. }
  410. function binaryJsToSt (selector) {
  411. return selector
  412. .replace(/^_/, '')
  413. .replace(/_and/g, '&')
  414. .replace(/_or/g, '|')
  415. .replace(/_plus/g, '+')
  416. .replace(/_minus/g, '-')
  417. .replace(/_star/g, '*')
  418. .replace(/_slash/g, '/')
  419. .replace(/_backslash/g, '\\')
  420. .replace(/_tild/g, '~')
  421. .replace(/_percent/g, '%')
  422. .replace(/_gt/g, '>')
  423. .replace(/_lt/g, '<')
  424. .replace(/_eq/g, '=')
  425. .replace(/_comma/g, ',')
  426. .replace(/_at/g, '@');
  427. }
  428. st.st2prop = function (stSelector) {
  429. var colonPosition = stSelector.indexOf(':');
  430. return colonPosition === -1 ? stSelector : stSelector.slice(0, colonPosition);
  431. };
  432. }
  433. /* Making smalltalk that has basic building blocks */
  434. function configureWithFundamentals (brikz) {
  435. brikz.smalltalkGlobals = SmalltalkGlobalsBrik;
  436. brikz.root = RootBrik;
  437. brikz.arraySet = ArraySetBrik;
  438. brikz.organize = OrganizeBrik;
  439. brikz.selectorConversion = SelectorConversionBrik;
  440. brikz.selectors = SelectorsBrik;
  441. brikz.packages = PackagesBrik;
  442. brikz.composition = MethodCompositionBrik;
  443. brikz.behaviors = BehaviorsBrik;
  444. brikz.methods = MethodsBrik;
  445. brikz.rebuild();
  446. }
  447. return configureWithFundamentals;
  448. });