kernel-fundamentals.js 21 KB

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