1
0

kernel-fundamentals.js 20 KB

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