kernel-fundamentals.js 21 KB

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