kernel-language.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. //jshint eqnull:true
  2. define(['./kernel-goodies'], function ($goodies) {
  3. "use strict";
  4. var inherits = $goodies.inherits;
  5. var installMethodOfJsClass = $goodies.installMethodOfJsClass;
  6. var addElement = $goodies.addElement;
  7. var removeElement = $goodies.removeElement;
  8. MethodCompositionBrik.deps = ["methods"];
  9. function MethodCompositionBrik (brikz, st) {
  10. var updateMethod = brikz.methods.updateMethod;
  11. function aliased (selector, method) {
  12. var result = st.method(method, method.instantiateFn);
  13. if (method.selector !== selector) {
  14. result.selector = selector;
  15. result.source = '"Aliased as ' + selector + '"\n' + method.source;
  16. }
  17. result.owner = method.owner;
  18. return result;
  19. }
  20. function deleteKeysFrom (keys, obj) {
  21. keys.forEach(function (each) {
  22. delete obj[each];
  23. });
  24. }
  25. function fillTraitTransformation (traitTransformation, obj) {
  26. // assert(Object.getOwnProperties(obj).length === 0)
  27. var traitMethods = traitTransformation.trait.methods;
  28. Object.keys(traitMethods).forEach(function (selector) {
  29. obj[selector] = aliased(selector, traitMethods[selector]);
  30. });
  31. var traitAliases = traitTransformation.aliases;
  32. if (traitAliases) {
  33. Object.keys(traitAliases).forEach(function (aliasSelector) {
  34. var aliasedMethod = traitMethods[traitAliases[aliasSelector]];
  35. if (aliasedMethod) obj[aliasSelector] = aliased(aliasSelector, aliasedMethod);
  36. // else delete obj[aliasSelector]; // semantically correct; optimized away
  37. });
  38. }
  39. var traitExclusions = traitTransformation.exclusions;
  40. if (traitExclusions) {
  41. deleteKeysFrom(traitExclusions, obj);
  42. }
  43. return obj;
  44. }
  45. function buildCompositionChain (traitComposition) {
  46. return traitComposition.reduce(function (soFar, each) {
  47. return fillTraitTransformation(each, Object.create(soFar));
  48. }, null);
  49. }
  50. st.setTraitComposition = function (traitComposition, traitOrBehavior) {
  51. var oldLocalMethods = traitOrBehavior.localMethods,
  52. newLocalMethods = Object.create(buildCompositionChain(traitComposition));
  53. Object.keys(oldLocalMethods).forEach(function (selector) {
  54. newLocalMethods[selector] = oldLocalMethods[selector];
  55. });
  56. var selector;
  57. traitOrBehavior.localMethods = newLocalMethods;
  58. for (selector in newLocalMethods) {
  59. updateMethod(selector, traitOrBehavior);
  60. }
  61. for (selector in oldLocalMethods) {
  62. updateMethod(selector, traitOrBehavior);
  63. }
  64. (traitOrBehavior.traitComposition || []).forEach(function (each) {
  65. removeElement(each.trait.traitUsers, traitOrBehavior);
  66. });
  67. traitOrBehavior.traitComposition = traitComposition && traitComposition.length ? traitComposition : null;
  68. (traitOrBehavior.traitComposition || []).forEach(function (each) {
  69. addElement(each.trait.traitUsers, traitOrBehavior);
  70. });
  71. };
  72. function aliasesOfSelector (selector, traitAliases) {
  73. if (!traitAliases) return [selector];
  74. var result = Object.keys(traitAliases).filter(function (aliasSelector) {
  75. return traitAliases[aliasSelector] === selector
  76. });
  77. if (!traitAliases[selector]) result.push(selector);
  78. return result;
  79. }
  80. function applyTraitMethodAddition (selector, method, traitTransformation, obj) {
  81. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  82. changes.forEach(function (aliasSelector) {
  83. obj[aliasSelector] = aliased(aliasSelector, method);
  84. });
  85. var traitExclusions = traitTransformation.exclusions;
  86. if (traitExclusions) {
  87. deleteKeysFrom(traitExclusions, obj);
  88. }
  89. return changes;
  90. }
  91. function applyTraitMethodDeletion (selector, traitTransformation, obj) {
  92. var changes = aliasesOfSelector(selector, traitTransformation.aliases);
  93. deleteKeysFrom(changes, obj);
  94. return changes;
  95. }
  96. function traitMethodChanged (selector, method, trait, traitOrBehavior) {
  97. var traitComposition = traitOrBehavior.traitComposition,
  98. chain = traitOrBehavior.localMethods,
  99. changes = [];
  100. for (var i = traitComposition.length - 1; i >= 0; --i) {
  101. chain = Object.getPrototypeOf(chain);
  102. var traitTransformation = traitComposition[i];
  103. if (traitTransformation.trait !== trait) continue;
  104. changes.push.apply(changes, method ?
  105. applyTraitMethodAddition(selector, method, traitTransformation, chain) :
  106. applyTraitMethodDeletion(selector, traitTransformation, chain));
  107. }
  108. // assert(chain === null);
  109. changes.forEach(function (each) {
  110. updateMethod(each, traitOrBehavior);
  111. });
  112. }
  113. this.traitMethodChanged = traitMethodChanged;
  114. }
  115. function LanguageFactory (specialConstructors, emit) {
  116. TraitsBrik.deps = ["event", "behaviors", "methods", "composition", "root"];
  117. function TraitsBrik (brikz, st) {
  118. var SmalltalkObject = brikz.root.Object;
  119. var setupMethods = brikz.methods.setupMethods;
  120. var traitMethodChanged = brikz.composition.traitMethodChanged;
  121. var buildTraitOrClass = brikz.behaviors.buildTraitOrClass;
  122. var declareEvent = brikz.event.declareEvent;
  123. function SmalltalkTrait () {
  124. }
  125. specialConstructors.Trait = inherits(SmalltalkTrait, SmalltalkObject);
  126. SmalltalkTrait.prototype.trait = true;
  127. installMethodOfJsClass(SmalltalkTrait, "toString", function () {
  128. return 'Smalltalk Trait ' + this.name;
  129. });
  130. declareEvent("traitAdded");
  131. installMethodOfJsClass(SmalltalkTrait, "added", function () {
  132. emit.traitAdded(this);
  133. });
  134. declareEvent("traitRemoved");
  135. installMethodOfJsClass(SmalltalkTrait, "removed", function () {
  136. emit.traitRemoved(this);
  137. });
  138. declareEvent("traitMethodAdded");
  139. installMethodOfJsClass(SmalltalkTrait, "methodAdded", function (method) {
  140. var self = this;
  141. this.traitUsers.forEach(function (each) {
  142. traitMethodChanged(method.selector, method, self, each);
  143. });
  144. emit.traitMethodAdded(method, this);
  145. });
  146. declareEvent("traitMethodRemoved");
  147. installMethodOfJsClass(SmalltalkTrait, "methodRemoved", function (method) {
  148. var self = this;
  149. this.traitUsers.forEach(function (each) {
  150. traitMethodChanged(method.selector, null, self, each);
  151. });
  152. emit.traitMethodRemoved(method, this);
  153. });
  154. function traitBuilder (traitName) {
  155. return {
  156. name: traitName,
  157. make: function () {
  158. var that = new SmalltalkTrait();
  159. that.name = traitName;
  160. that.traitUsers = [];
  161. setupMethods(that);
  162. return that;
  163. },
  164. updateExisting: function (trait) {
  165. }
  166. };
  167. }
  168. st.addTrait = function (className, category) {
  169. return buildTraitOrClass(category, traitBuilder(className));
  170. };
  171. }
  172. ClassesBrik.deps = ["root", "event", "behaviors", "methods", "nil"];
  173. function ClassesBrik (brikz, st) {
  174. var SmalltalkRoot = brikz.root.Root;
  175. var SmalltalkObject = brikz.root.Object;
  176. var buildTraitOrClass = brikz.behaviors.buildTraitOrClass;
  177. var setupMethods = brikz.methods.setupMethods;
  178. var removeTraitOrClass = brikz.behaviors.removeTraitOrClass;
  179. var declareEvent = brikz.event.declareEvent;
  180. var nilAsReceiver = brikz.nil.nilAsReceiver;
  181. function SmalltalkBehavior () {
  182. }
  183. function SmalltalkClass () {
  184. }
  185. function SmalltalkMetaclass () {
  186. }
  187. specialConstructors.Behavior = inherits(SmalltalkBehavior, SmalltalkObject);
  188. specialConstructors.Class = inherits(SmalltalkClass, SmalltalkBehavior);
  189. specialConstructors.Metaclass = inherits(SmalltalkMetaclass, SmalltalkBehavior);
  190. // Fake root class of the system.
  191. // Effective superclass of all classes created with `nil subclass: ...`.
  192. var nilAsClass = this.nilAsClass = {
  193. fn: SmalltalkRoot,
  194. subclasses: [],
  195. a$cls: {fn: SmalltalkClass}
  196. };
  197. SmalltalkMetaclass.prototype.meta = true;
  198. installMethodOfJsClass(SmalltalkClass, "toString", function () {
  199. return 'Smalltalk ' + this.name;
  200. });
  201. installMethodOfJsClass(SmalltalkMetaclass, "toString", function () {
  202. return 'Smalltalk Metaclass ' + this.instanceClass.name;
  203. });
  204. declareEvent("classAdded");
  205. installMethodOfJsClass(SmalltalkClass, "added", function () {
  206. addSubclass(this);
  207. emit.classAdded(this);
  208. });
  209. declareEvent("classRemoved");
  210. installMethodOfJsClass(SmalltalkClass, "removed", function () {
  211. emit.classRemoved(this);
  212. removeSubclass(this);
  213. });
  214. declareEvent("behaviorMethodAdded");
  215. installMethodOfJsClass(SmalltalkBehavior, "methodAdded", function (method) {
  216. emit.behaviorMethodAdded(method, this);
  217. });
  218. declareEvent("behaviorMethodRemove");
  219. installMethodOfJsClass(SmalltalkBehavior, "methodRemoved", function (method) {
  220. emit.behaviorMethodRemoved(method, this);
  221. });
  222. // TODO remove, ["@foo"] backward compatibility
  223. function installIvarCompat (klass) {
  224. var ivars = klass.slots;
  225. ivars.forEach(function (ivar) {
  226. Object.defineProperty(klass.fn.prototype, "@" + ivar, {
  227. get: function () {
  228. return this[ivar];
  229. },
  230. set: function (value) {
  231. return this[ivar] = value;
  232. },
  233. enumerable: false,
  234. configurable: true
  235. });
  236. });
  237. }
  238. this.installIvarCompat = installIvarCompat;
  239. function setSlots (klass, slots) {
  240. slots.forEach(function (name) {
  241. if (!name.match(/^[a-zA-Z][a-zA-Z0-9]*$/))
  242. throw new Error("Wrong identifier name: " + name);
  243. });
  244. klass.slots = slots;
  245. installIvarCompat(klass);
  246. }
  247. st.setSlots = setSlots;
  248. // TODO remove, .iVarNames backward compatibility
  249. Object.defineProperty(SmalltalkBehavior.prototype, "iVarNames", {
  250. enumerable: true,
  251. configurable: true,
  252. get: function () {
  253. return this.slots;
  254. },
  255. set: function (instanceVariableNames) {
  256. setSlots(this, instanceVariableNames);
  257. }
  258. });
  259. this.bootstrapHierarchy = function (realClass) {
  260. nilAsClass.a$cls = realClass;
  261. nilAsClass.subclasses.forEach(function (each) {
  262. each.a$cls.superclass = realClass;
  263. addSubclass(each.a$cls);
  264. });
  265. };
  266. /* Smalltalk class creation. A class is an instance of an automatically
  267. created metaclass object. Newly created classes (not their metaclass)
  268. should be added to the system, see smalltalk.addClass().
  269. Superclass linking is *not* handled here, see api.initialize() */
  270. function classBuilder (className, superclass, fn) {
  271. var logicalSuperclass = superclass;
  272. if (superclass == null || superclass.a$nil) {
  273. superclass = nilAsClass;
  274. logicalSuperclass = null;
  275. }
  276. function klass () {
  277. var that = metaclass().instanceClass;
  278. that.superclass = logicalSuperclass;
  279. that.fn = fn || inherits(function () {
  280. }, superclass.fn);
  281. that.slots = [];
  282. that.name = className;
  283. that.subclasses = [];
  284. setupMethods(that);
  285. return that;
  286. }
  287. function metaclass () {
  288. var that = new SmalltalkMetaclass();
  289. that.superclass = superclass.a$cls;
  290. that.fn = inherits(function () {
  291. }, that.superclass.fn);
  292. that.slots = [];
  293. that.instanceClass = new that.fn();
  294. wireKlass(that);
  295. setupMethods(that);
  296. return that;
  297. }
  298. return {
  299. name: className,
  300. make: klass,
  301. updateExisting: function (klass) {
  302. if (klass.superclass != logicalSuperclass || fn && fn !== klass.fn)
  303. throw new Error("Incompatible change of class: " + klass.name);
  304. }
  305. };
  306. }
  307. function wireKlass (klass) {
  308. Object.defineProperty(klass.fn.prototype, "a$cls", {
  309. value: klass,
  310. enumerable: false, configurable: true, writable: true
  311. });
  312. }
  313. this.wireKlass = wireKlass;
  314. /**
  315. * This function is used all over the compiled amber code.
  316. * It takes any value (JavaScript or Smalltalk)
  317. * and returns a proper Amber Smalltalk receiver.
  318. *
  319. * null or undefined -> nilAsReceiver,
  320. * object having Smalltalk signature -> unchanged,
  321. * otherwise wrapped foreign (JS) object
  322. */
  323. this.asReceiver = function (o) {
  324. if (o == null) return nilAsReceiver;
  325. else if (o.a$cls != null) return o;
  326. else return st.wrapJavaScript(o);
  327. };
  328. /* Add a class to the system, creating a new one if needed.
  329. A Package is lazily created if one with given name does not exist. */
  330. st.addClass = function (className, superclass, category) {
  331. // TODO remove, backward compatibility
  332. if (arguments[3]) {
  333. var added = st.addClass(className, superclass, arguments[3]);
  334. setSlots(added, category);
  335. return added;
  336. }
  337. // While subclassing nil is allowed, it might be an error, so
  338. // warn about it.
  339. if (typeof superclass === 'undefined' || superclass && superclass.a$nil) {
  340. console.warn('Compiling ' + className + ' as a subclass of `nil`. A dependency might be missing.');
  341. }
  342. return buildTraitOrClass(category, classBuilder(className, superclass, specialConstructors[className]));
  343. };
  344. st.removeClass = removeTraitOrClass;
  345. function addSubclass (klass) {
  346. addElement((klass.superclass || nilAsClass).subclasses, klass);
  347. }
  348. function removeSubclass (klass) {
  349. removeElement((klass.superclass || nilAsClass).subclasses, klass);
  350. }
  351. function metaSubclasses (metaclass) {
  352. return metaclass.instanceClass.subclasses
  353. .filter(function (each) {
  354. return !each.meta;
  355. })
  356. .map(function (each) {
  357. return each.a$cls;
  358. });
  359. }
  360. st.metaSubclasses = metaSubclasses;
  361. st.traverseClassTree = function (klass, fn) {
  362. var queue = [klass], sentinel = {};
  363. for (var i = 0; i < queue.length; ++i) {
  364. var item = queue[i];
  365. if (fn(item, sentinel) === sentinel) continue;
  366. var subclasses = item.meta ? metaSubclasses(item) : item.subclasses;
  367. queue.push.apply(queue, subclasses);
  368. }
  369. };
  370. }
  371. /* Making smalltalk that can load */
  372. function configure (brikz) {
  373. brikz.traits = TraitsBrik;
  374. brikz.composition = MethodCompositionBrik;
  375. brikz.classes = ClassesBrik;
  376. brikz();
  377. }
  378. return {configure: configure};
  379. }
  380. return LanguageFactory;
  381. });