kernel-language.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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(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 defineMethod (klass, name, method) {
  51. Object.defineProperty(klass.prototype, name, {
  52. value: method,
  53. enumerable: false, configurable: true, writable: true
  54. });
  55. }
  56. TraitsBrik.deps = ["event", "behaviors", "methods", "composition", "root"];
  57. function TraitsBrik (brikz, st) {
  58. var coreFns = brikz.root.coreFns;
  59. var SmalltalkObject = brikz.root.Object;
  60. var setupMethods = brikz.methods.setupMethods;
  61. var traitMethodChanged = brikz.composition.traitMethodChanged;
  62. var buildTraitOrClass = brikz.behaviors.buildTraitOrClass;
  63. var emit = brikz.event.emit;
  64. var declareEvent = brikz.event.declareEvent;
  65. function SmalltalkTrait () {
  66. }
  67. coreFns.Trait = inherits(SmalltalkTrait, SmalltalkObject);
  68. SmalltalkTrait.prototype.trait = true;
  69. defineMethod(SmalltalkTrait, "toString", function () {
  70. return 'Smalltalk Trait ' + this.name;
  71. });
  72. declareEvent("traitAdded");
  73. defineMethod(SmalltalkTrait, "added", function () {
  74. emit.traitAdded(this);
  75. });
  76. declareEvent("traitRemoved");
  77. defineMethod(SmalltalkTrait, "removed", function () {
  78. emit.traitRemoved(this);
  79. });
  80. declareEvent("traitMethodAdded");
  81. defineMethod(SmalltalkTrait, "methodAdded", function (method) {
  82. var self = this;
  83. this.traitUsers.forEach(function (each) {
  84. traitMethodChanged(method.selector, method, self, each);
  85. });
  86. emit.traitMethodAdded(method, this);
  87. });
  88. declareEvent("traitMethodRemoved");
  89. defineMethod(SmalltalkTrait, "methodRemoved", function (method) {
  90. var self = this;
  91. this.traitUsers.forEach(function (each) {
  92. traitMethodChanged(method.selector, null, self, each);
  93. });
  94. emit.traitMethodRemoved(method, this);
  95. });
  96. function traitBuilder (traitName) {
  97. return {
  98. name: traitName,
  99. make: function () {
  100. var that = new SmalltalkTrait();
  101. that.name = traitName;
  102. that.traitUsers = [];
  103. setupMethods(that);
  104. return that;
  105. },
  106. updateExisting: function (trait) {
  107. }
  108. };
  109. }
  110. st.addTrait = function (className, category) {
  111. return buildTraitOrClass(category, traitBuilder(className));
  112. };
  113. }
  114. MethodCompositionBrik.deps = ["methods", "arraySet"];
  115. function MethodCompositionBrik (brikz, st) {
  116. var updateMethod = brikz.methods.updateMethod;
  117. var addElement = brikz.arraySet.addElement;
  118. var removeElement = brikz.arraySet.removeElement;
  119. function aliased (selector, method) {
  120. if (method.selector === selector) return method;
  121. var result = st.method({
  122. selector: selector,
  123. args: method.args,
  124. protocol: method.protocol,
  125. source: '"Aliased as ' + selector + '"\n' + method.source,
  126. messageSends: method.messageSends,
  127. referencesClasses: method.referencedClasses,
  128. fn: method.fn
  129. });
  130. result.owner = method.owner;
  131. return result;
  132. }
  133. function deleteKeysFrom (keys, obj) {
  134. keys.forEach(function (each) {
  135. delete obj[each];
  136. });
  137. }
  138. function fillTraitTransformation (traitTransformation, obj) {
  139. // assert(Object.getOwnProperties(obj).length === 0)
  140. var traitMethods = traitTransformation.trait.methods;
  141. Object.keys(traitMethods).forEach(function (selector) {
  142. obj[selector] = traitMethods[selector];
  143. });
  144. var traitAliases = traitTransformation.aliases;
  145. if (traitAliases) {
  146. Object.keys(traitAliases).forEach(function (aliasSelector) {
  147. var aliasedMethod = traitMethods[traitAliases[aliasSelector]];
  148. if (aliasedMethod) obj[aliasSelector] = aliased(aliasSelector, aliasedMethod);
  149. // else delete obj[aliasSelector]; // semantically correct; optimized away
  150. });
  151. }
  152. var traitExclusions = traitTransformation.exclusions;
  153. if (traitExclusions) {
  154. deleteKeysFrom(traitExclusions, obj);
  155. }
  156. return obj;
  157. }
  158. function buildCompositionChain (traitComposition) {
  159. return traitComposition.reduce(function (soFar, each) {
  160. return fillTraitTransformation(each, Object.create(soFar));
  161. }, null);
  162. }
  163. st.setTraitComposition = function (traitComposition, traitOrBehavior) {
  164. var oldLocalMethods = traitOrBehavior.localMethods,
  165. newLocalMethods = Object.create(buildCompositionChain(traitComposition));
  166. Object.keys(oldLocalMethods).forEach(function (selector) {
  167. newLocalMethods[selector] = oldLocalMethods[selector];
  168. });
  169. var selector;
  170. traitOrBehavior.localMethods = newLocalMethods;
  171. for (selector in newLocalMethods) {
  172. updateMethod(selector, traitOrBehavior);
  173. }
  174. for (selector in oldLocalMethods) {
  175. updateMethod(selector, traitOrBehavior);
  176. }
  177. (traitOrBehavior.traitComposition || []).forEach(function (each) {
  178. removeElement(each.trait.traitUsers, traitOrBehavior);
  179. });
  180. traitOrBehavior.traitComposition = traitComposition && traitComposition.length ? traitComposition : null;
  181. (traitOrBehavior.traitComposition || []).forEach(function (each) {
  182. addElement(each.trait.traitUsers, traitOrBehavior);
  183. });
  184. };
  185. function aliasesOfSelector (selector, traitAliases) {
  186. if (!traitAliases) return [selector];
  187. var result = Object.keys(traitAliases).filter(function (aliasSelector) {
  188. return traitAliases[aliasSelector] === selector
  189. });
  190. if (!traitAliases[selector]) result.push(selector);
  191. return result;
  192. }
  193. function applyTraitMethodAddition (selector, method, traitTransformation, obj) {
  194. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  195. changes.forEach(function (aliasSelector) {
  196. obj[aliasSelector] = aliased(aliasSelector, method);
  197. });
  198. var traitExclusions = traitTransformation.exclusions;
  199. if (traitExclusions) {
  200. deleteKeysFrom(traitExclusions, obj);
  201. }
  202. return changes;
  203. }
  204. function applyTraitMethodDeletion (selector, traitTransformation, obj) {
  205. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  206. deleteKeysFrom(changes, obj);
  207. return changes;
  208. }
  209. function traitMethodChanged (selector, method, trait, traitOrBehavior) {
  210. var traitComposition = traitOrBehavior.traitComposition,
  211. chain = traitOrBehavior.localMethods,
  212. changes = [];
  213. for (var i = traitComposition.length - 1; i >= 0; --i) {
  214. chain = Object.getPrototypeOf(chain);
  215. var traitTransformation = traitComposition[i];
  216. if (traitTransformation.trait !== trait) continue;
  217. changes.push.apply(changes, method ?
  218. applyTraitMethodAddition(selector, method, traitTransformation, chain) :
  219. applyTraitMethodDeletion(selector, traitTransformation, chain));
  220. }
  221. // assert(chain === null);
  222. changes.forEach(function (each) {
  223. updateMethod(each, traitOrBehavior);
  224. });
  225. }
  226. this.traitMethodChanged = traitMethodChanged;
  227. }
  228. ClassesBrik.deps = ["root", "event", "behaviors", "methods", "arraySet", "smalltalkGlobals"];
  229. function ClassesBrik (brikz, st) {
  230. var SmalltalkRoot = brikz.root.Root;
  231. var coreFns = brikz.root.coreFns;
  232. var globals = brikz.smalltalkGlobals.globals;
  233. var SmalltalkObject = brikz.root.Object;
  234. var buildTraitOrClass = brikz.behaviors.buildTraitOrClass;
  235. var setupMethods = brikz.methods.setupMethods;
  236. var removeTraitOrClass = brikz.behaviors.removeTraitOrClass;
  237. var addElement = brikz.arraySet.addElement;
  238. var removeElement = brikz.arraySet.removeElement;
  239. var emit = brikz.event.emit;
  240. var declareEvent = brikz.event.declareEvent;
  241. function SmalltalkBehavior () {
  242. }
  243. function SmalltalkClass () {
  244. }
  245. function SmalltalkMetaclass () {
  246. }
  247. coreFns.Behavior = inherits(SmalltalkBehavior, SmalltalkObject);
  248. coreFns.Class = inherits(SmalltalkClass, SmalltalkBehavior);
  249. coreFns.Metaclass = inherits(SmalltalkMetaclass, SmalltalkBehavior);
  250. // Fake root class of the system.
  251. // Effective superclass of all classes created with `nil subclass: ...`.
  252. var nilAsClass = this.nilAsClass = {
  253. fn: SmalltalkRoot,
  254. a$cls: {fn: SmalltalkClass}
  255. };
  256. SmalltalkMetaclass.prototype.meta = true;
  257. defineMethod(SmalltalkClass, "toString", function () {
  258. return 'Smalltalk ' + this.name;
  259. });
  260. defineMethod(SmalltalkMetaclass, "toString", function () {
  261. return 'Smalltalk Metaclass ' + this.instanceClass.name;
  262. });
  263. declareEvent("classAdded");
  264. defineMethod(SmalltalkClass, "added", function () {
  265. addSubclass(this);
  266. emit.classAdded(this);
  267. });
  268. declareEvent("classRemoved");
  269. defineMethod(SmalltalkClass, "removed", function () {
  270. emit.classRemoved(this);
  271. removeSubclass(this);
  272. });
  273. declareEvent("behaviorMethodAdded");
  274. defineMethod(SmalltalkBehavior, "methodAdded", function (method) {
  275. emit.behaviorMethodAdded(method, this);
  276. });
  277. declareEvent("behaviorMethodRemove");
  278. defineMethod(SmalltalkBehavior, "methodRemoved", function (method) {
  279. emit.behaviorMethodRemoved(method, this);
  280. });
  281. // TODO remove, ["@foo"] backward compatibility
  282. function installIvarCompat (klass) {
  283. var ivars = klass.slots;
  284. ivars.forEach(function (ivar) {
  285. Object.defineProperty(klass.fn.prototype, "@" + ivar, {
  286. get: function () {
  287. return this[ivar];
  288. },
  289. set: function (value) {
  290. return this[ivar] = value;
  291. },
  292. enumerable: false,
  293. configurable: true
  294. });
  295. });
  296. }
  297. this.installIvarCompat = installIvarCompat;
  298. function setSlots (klass, slots) {
  299. slots.forEach(function (name) {
  300. if (!name.match(/^[a-zA-Z][a-zA-Z0-9]*$/))
  301. throw new Error("Wrong identifier name: " + name);
  302. });
  303. klass.slots = slots;
  304. installIvarCompat(klass);
  305. }
  306. st.setSlots = setSlots;
  307. // TODO remove, .iVarNames backward compatibility
  308. Object.defineProperty(SmalltalkBehavior.prototype, "iVarNames", {
  309. enumerable: true,
  310. configurable: true,
  311. get: function () {
  312. return this.slots;
  313. },
  314. set: function (instanceVariableNames) {
  315. setSlots(this, instanceVariableNames);
  316. }
  317. });
  318. this.bootstrapHierarchy = function () {
  319. var nilSubclasses = [globals.ProtoObject];
  320. nilAsClass.a$cls = globals.Class;
  321. nilSubclasses.forEach(function (each) {
  322. each.a$cls.superclass = globals.Class;
  323. addSubclass(each.a$cls);
  324. });
  325. };
  326. /* Smalltalk class creation. A class is an instance of an automatically
  327. created metaclass object. Newly created classes (not their metaclass)
  328. should be added to the system, see smalltalk.addClass().
  329. Superclass linking is *not* handled here, see api.initialize() */
  330. function classBuilder (className, superclass, fn) {
  331. var logicalSuperclass = superclass;
  332. if (superclass == null || superclass.a$nil) {
  333. superclass = nilAsClass;
  334. logicalSuperclass = null;
  335. }
  336. function klass () {
  337. var that = metaclass().instanceClass;
  338. that.superclass = logicalSuperclass;
  339. that.fn = fn || inherits(function () {
  340. }, superclass.fn);
  341. that.slots = [];
  342. that.name = className;
  343. that.subclasses = [];
  344. setupMethods(that);
  345. return that;
  346. }
  347. function metaclass () {
  348. var that = new SmalltalkMetaclass();
  349. that.superclass = superclass.a$cls;
  350. that.fn = inherits(function () {
  351. }, that.superclass.fn);
  352. that.slots = [];
  353. that.instanceClass = new that.fn();
  354. wireKlass(that);
  355. setupMethods(that);
  356. return that;
  357. }
  358. return {
  359. name: className,
  360. make: klass,
  361. updateExisting: function (klass) {
  362. if (klass.superclass != logicalSuperclass || fn && fn !== klass.fn)
  363. throw new Error("Incompatible change of class: " + klass.name);
  364. }
  365. };
  366. }
  367. function wireKlass (klass) {
  368. Object.defineProperty(klass.fn.prototype, "a$cls", {
  369. value: klass,
  370. enumerable: false, configurable: true, writable: true
  371. });
  372. }
  373. this.wireKlass = wireKlass;
  374. /* Add a class to the system, creating a new one if needed.
  375. A Package is lazily created if one with given name does not exist. */
  376. st.addClass = function (className, superclass, category) {
  377. // TODO remove, backward compatibility
  378. if (arguments[3]) {
  379. var added = st.addClass(className, superclass, arguments[3]);
  380. setSlots(added, category);
  381. return added;
  382. }
  383. // While subclassing nil is allowed, it might be an error, so
  384. // warn about it.
  385. if (typeof superclass === 'undefined' || superclass && superclass.a$nil) {
  386. console.warn('Compiling ' + className + ' as a subclass of `nil`. A dependency might be missing.');
  387. }
  388. return buildTraitOrClass(category, classBuilder(className, superclass, coreFns[className]));
  389. };
  390. st.removeClass = removeTraitOrClass;
  391. function addSubclass (klass) {
  392. if (klass.superclass) {
  393. addElement(klass.superclass.subclasses, klass);
  394. }
  395. }
  396. function removeSubclass (klass) {
  397. if (klass.superclass) {
  398. removeElement(klass.superclass.subclasses, klass);
  399. }
  400. }
  401. function metaSubclasses (metaclass) {
  402. return metaclass.instanceClass.subclasses
  403. .filter(function (each) {
  404. return !each.meta;
  405. })
  406. .map(function (each) {
  407. return each.a$cls;
  408. });
  409. }
  410. st.metaSubclasses = metaSubclasses;
  411. st.traverseClassTree = function (klass, fn) {
  412. var queue = [klass], sentinel = {};
  413. for (var i = 0; i < queue.length; ++i) {
  414. var item = queue[i];
  415. if (fn(item, sentinel) === sentinel) continue;
  416. var subclasses = item.meta ? metaSubclasses(item) : item.subclasses;
  417. queue.push.apply(queue, subclasses);
  418. }
  419. };
  420. }
  421. /* Making smalltalk that can load */
  422. function configureWithHierarchy (brikz) {
  423. brikz.traits = TraitsBrik;
  424. brikz.composition = MethodCompositionBrik;
  425. brikz.classes = ClassesBrik;
  426. brikz.rebuild();
  427. }
  428. return configureWithHierarchy;
  429. });