kernel-language.js 18 KB

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