kernel-fundamentals.js 20 KB

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