kernel-fundamentals.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 = ["behaviorProviders", "selectors", "root", "selectorConversion"];
  167. function MethodsBrik (brikz, st) {
  168. var registerSelector = brikz.selectors.registerSelector;
  169. var updateMethod = brikz.behaviorProviders.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. BehaviorProvidersBrik.deps = ["organize"];
  219. function BehaviorProvidersBrik (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 updateMethod (selector, traitOrBehavior) {
  242. var oldMethod = traitOrBehavior.methods[selector],
  243. newMethod = traitOrBehavior.localMethods[selector];
  244. if (oldMethod == null && newMethod == null) {
  245. console.warn("Removal of nonexistent method " + traitOrBehavior + " >> " + selector);
  246. return;
  247. }
  248. if (newMethod === oldMethod) return;
  249. if (newMethod != null) addMethod(newMethod, traitOrBehavior);
  250. else removeMethod(oldMethod, traitOrBehavior);
  251. }
  252. this.updateMethod = updateMethod;
  253. }
  254. MethodCompositionBrik.deps = ["behaviorProviders"];
  255. function MethodCompositionBrik (brikz, st) {
  256. var updateMethod = brikz.behaviorProviders.updateMethod;
  257. function aliased (selector, method) {
  258. if (method.selector === selector) return method;
  259. var result = st.method({
  260. selector: selector,
  261. args: method.args,
  262. protocol: method.protocol,
  263. source: '"Aliased as ' + selector + '"\n' + method.source,
  264. messageSends: method.messageSends,
  265. referencesClasses: method.referencedClasses,
  266. fn: method.fn
  267. });
  268. result.methodClass = method.methodClass;
  269. return result;
  270. }
  271. function deleteKeysFrom (keys, obj) {
  272. keys.forEach(function (each) {
  273. delete obj[each];
  274. });
  275. }
  276. // TODO move trait transformation application to own brik in kernel-languages.js
  277. function fillTraitTransformation (traitTransformation, obj) {
  278. // assert(Object.getOwnProperties(obj).length === 0)
  279. var traitMethods = traitTransformation.trait.methods;
  280. Object.keys(traitMethods).forEach(function (selector) {
  281. obj[selector] = traitMethods[selector];
  282. });
  283. var traitAliases = traitTransformation.aliases;
  284. if (traitAliases) {
  285. Object.keys(traitAliases).forEach(function (aliasSelector) {
  286. var aliasedMethod = traitMethods[traitAliases[aliasSelector]];
  287. if (aliasedMethod) obj[aliasSelector] = aliased(aliasSelector, aliasedMethod);
  288. // else delete obj[aliasSelector]; // semantically correct; optimized away
  289. });
  290. }
  291. var traitExclusions = traitTransformation.exclusions;
  292. if (traitExclusions) {
  293. deleteKeysFrom(traitExclusions, obj);
  294. }
  295. return obj;
  296. }
  297. function buildCompositionChain (traitComposition) {
  298. return traitComposition.reduce(function (soFar, each) {
  299. return fillTraitTransformation(each, Object.create(soFar));
  300. }, null);
  301. }
  302. st.setTraitComposition = function (traitComposition, traitOrBehavior) {
  303. var oldLocalMethods = traitOrBehavior.localMethods,
  304. newLocalMethods = Object.create(buildCompositionChain(traitComposition));
  305. Object.keys(oldLocalMethods).forEach(function (selector) {
  306. newLocalMethods[selector] = oldLocalMethods[selector];
  307. });
  308. var selector;
  309. traitOrBehavior.localMethods = newLocalMethods;
  310. for (selector in newLocalMethods) {
  311. updateMethod(selector, traitOrBehavior);
  312. }
  313. for (selector in oldLocalMethods) {
  314. updateMethod(selector, traitOrBehavior);
  315. }
  316. traitOrBehavior.traitComposition.forEach(function (each) {
  317. each.trait.removeUser(traitOrBehavior);
  318. });
  319. traitOrBehavior.traitComposition = traitComposition;
  320. traitOrBehavior.traitComposition.forEach(function (each) {
  321. each.trait.addUser(traitOrBehavior);
  322. });
  323. };
  324. function aliasesOfSelector (selector, traitAliases) {
  325. if (!traitAliases) return [selector];
  326. var result = Object.keys(traitAliases).filter(function (aliasSelector) {
  327. return traitAliases[aliasSelector] === selector
  328. });
  329. if (!traitAliases[selector]) result.push(selector);
  330. return result;
  331. }
  332. function applyTraitMethodAddition (selector, method, traitTransformation, obj) {
  333. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  334. changes.forEach(function (aliasSelector) {
  335. obj[aliasSelector] = aliased(aliasSelector, method);
  336. });
  337. var traitExclusions = traitTransformation.exclusions;
  338. if (traitExclusions) {
  339. deleteKeysFrom(traitExclusions, obj);
  340. }
  341. return changes;
  342. }
  343. function applyTraitMethodDeletion (selector, traitTransformation, obj) {
  344. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  345. deleteKeysFrom(changes, obj);
  346. return changes;
  347. }
  348. function traitMethodChanged (selector, method, trait, traitOrBehavior) {
  349. var traitComposition = traitOrBehavior.traitComposition,
  350. chain = traitOrBehavior.localMethods,
  351. changes = [];
  352. for (var i = traitComposition.length - 1; i >= 0; --i) {
  353. chain = Object.getPrototypeOf(chain);
  354. var traitTransformation = traitComposition[i];
  355. if (traitTransformation.trait !== trait) continue;
  356. changes.push.apply(changes, method ?
  357. applyTraitMethodAddition(selector, method, traitTransformation, chain) :
  358. applyTraitMethodDeletion(selector, traitTransformation, chain));
  359. }
  360. // assert(chain === null);
  361. changes.forEach(function (each) {
  362. updateMethod(each, traitOrBehavior);
  363. });
  364. }
  365. this.traitMethodChanged = traitMethodChanged;
  366. }
  367. function ArraySetBrik (brikz, st) {
  368. st.addElement = this.addElement = function (array, el) {
  369. if (typeof el === 'undefined') {
  370. return;
  371. }
  372. if (array.indexOf(el) === -1) {
  373. array.push(el);
  374. }
  375. };
  376. st.removeElement = this.removeElement = function (array, el) {
  377. var i = array.indexOf(el);
  378. if (i !== -1) {
  379. array.splice(i, 1);
  380. }
  381. };
  382. }
  383. function SelectorConversionBrik (brikz, st) {
  384. /* Convert a Smalltalk selector into a JS selector */
  385. st.st2js = function (string) {
  386. return '_' + string
  387. .replace(/:/g, '_')
  388. .replace(/[\&]/g, '_and')
  389. .replace(/[\|]/g, '_or')
  390. .replace(/[+]/g, '_plus')
  391. .replace(/-/g, '_minus')
  392. .replace(/[*]/g, '_star')
  393. .replace(/[\/]/g, '_slash')
  394. .replace(/[\\]/g, '_backslash')
  395. .replace(/[\~]/g, '_tild')
  396. .replace(/%/g, '_percent')
  397. .replace(/>/g, '_gt')
  398. .replace(/</g, '_lt')
  399. .replace(/=/g, '_eq')
  400. .replace(/,/g, '_comma')
  401. .replace(/[@]/g, '_at');
  402. };
  403. /* Convert a string to a valid smalltalk selector.
  404. if you modify the following functions, also change st2js
  405. accordingly */
  406. st.js2st = function (selector) {
  407. if (selector.match(/^__/)) {
  408. return binaryJsToSt(selector);
  409. } else {
  410. return keywordJsToSt(selector);
  411. }
  412. };
  413. function keywordJsToSt (selector) {
  414. return selector.replace(/^_/, '').replace(/_/g, ':');
  415. }
  416. function binaryJsToSt (selector) {
  417. return selector
  418. .replace(/^_/, '')
  419. .replace(/_and/g, '&')
  420. .replace(/_or/g, '|')
  421. .replace(/_plus/g, '+')
  422. .replace(/_minus/g, '-')
  423. .replace(/_star/g, '*')
  424. .replace(/_slash/g, '/')
  425. .replace(/_backslash/g, '\\')
  426. .replace(/_tild/g, '~')
  427. .replace(/_percent/g, '%')
  428. .replace(/_gt/g, '>')
  429. .replace(/_lt/g, '<')
  430. .replace(/_eq/g, '=')
  431. .replace(/_comma/g, ',')
  432. .replace(/_at/g, '@');
  433. }
  434. st.st2prop = function (stSelector) {
  435. var colonPosition = stSelector.indexOf(':');
  436. return colonPosition === -1 ? stSelector : stSelector.slice(0, colonPosition);
  437. };
  438. }
  439. /* Making smalltalk that has basic building blocks */
  440. function configureWithFundamentals (brikz) {
  441. brikz.smalltalkGlobals = SmalltalkGlobalsBrik;
  442. brikz.root = RootBrik;
  443. brikz.arraySet = ArraySetBrik;
  444. brikz.organize = OrganizeBrik;
  445. brikz.selectorConversion = SelectorConversionBrik;
  446. brikz.selectors = SelectorsBrik;
  447. brikz.packages = PackagesBrik;
  448. brikz.composition = MethodCompositionBrik;
  449. brikz.behaviorProviders = BehaviorProvidersBrik;
  450. brikz.behaviors = BehaviorsBrik;
  451. brikz.methods = MethodsBrik;
  452. brikz.rebuild();
  453. }
  454. return configureWithFundamentals;
  455. });