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