kernel-fundamentals.js 21 KB

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