1
0

kernel-language.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. SmalltalkTrait.prototype.methodAdded = function (method) {
  136. propagateMethodChange(this, method.selector, method);
  137. };
  138. SmalltalkTrait.prototype.methodRemoved = function (method) {
  139. propagateMethodChange(this, method.selector, null);
  140. };
  141. function propagateMethodChange (trait, selector, method) {
  142. trait.traitUsers.forEach(function (each) {
  143. traitMethodChanged(selector, method, trait, each);
  144. });
  145. }
  146. function traitBuilder (traitName, category) {
  147. return {
  148. name: traitName,
  149. make: function () {
  150. var that = new SmalltalkTrait();
  151. that.name = traitName;
  152. that.category = category;
  153. that.traitUsers = [];
  154. setupMethods(that);
  155. return that;
  156. },
  157. updateExisting: function (trait) {
  158. }
  159. };
  160. }
  161. st.addTrait = function (className, category) {
  162. return buildTraitOrClass(traitBuilder(className, category));
  163. };
  164. }
  165. ClassModelBrik.deps = ["root", "nil"];
  166. function ClassModelBrik (brikz, st) {
  167. var SmalltalkRoot = brikz.root.Root;
  168. var SmalltalkObject = brikz.root.Object;
  169. var nilAsReceiver = brikz.nil.nilAsReceiver;
  170. function SmalltalkBehavior () {
  171. }
  172. function SmalltalkClass () {
  173. }
  174. function SmalltalkMetaclass () {
  175. }
  176. this.newMetaclass = function () {
  177. return new SmalltalkMetaclass();
  178. };
  179. specialConstructors.Behavior = inherits(SmalltalkBehavior, SmalltalkObject);
  180. specialConstructors.Class = inherits(SmalltalkClass, SmalltalkBehavior);
  181. specialConstructors.Metaclass = inherits(SmalltalkMetaclass, SmalltalkBehavior);
  182. SmalltalkMetaclass.prototype.meta = true;
  183. declareJsMethod(SmalltalkClass.prototype, "toString");
  184. declareJsMethod(SmalltalkMetaclass.prototype, "toString");
  185. declareJsMethod(SmalltalkClass.prototype, "added");
  186. declareJsMethod(SmalltalkClass.prototype, "removed");
  187. declareJsMethod(SmalltalkBehavior.prototype, "methodAdded");
  188. declareJsMethod(SmalltalkBehavior.prototype, "methodRemoved");
  189. SmalltalkClass.prototype.toString = function () {
  190. return 'Smalltalk ' + this.name;
  191. };
  192. SmalltalkMetaclass.prototype.toString = function () {
  193. return 'Smalltalk Metaclass ' + this.instanceClass.name;
  194. };
  195. declareEvent("classCreated");
  196. SmalltalkClass.prototype.added = function () {
  197. registerToSuperclass(this);
  198. emit.classCreated(this);
  199. };
  200. SmalltalkClass.prototype.removed = function () {
  201. unregisterFromSuperclass(this);
  202. };
  203. declareEvent("behaviorMethodAdded");
  204. SmalltalkBehavior.prototype.methodAdded = function (method) {
  205. emit.behaviorMethodAdded(method, this);
  206. };
  207. declareEvent("behaviorMethodRemoved");
  208. SmalltalkBehavior.prototype.methodRemoved = function (method) {
  209. emit.behaviorMethodRemoved(method, this);
  210. };
  211. // Fake root class of the system.
  212. // Effective superclass of all classes created with `nil subclass: ...`.
  213. var nilAsClass = this.nilAsClass = {
  214. fn: SmalltalkRoot,
  215. subclasses: [],
  216. a$cls: {fn: SmalltalkClass}
  217. };
  218. this.bootstrapHierarchy = function (realClass) {
  219. nilAsClass.a$cls = realClass;
  220. nilAsClass.subclasses.forEach(function (each) {
  221. each.a$cls.superclass = realClass;
  222. registerToSuperclass(each.a$cls);
  223. });
  224. };
  225. function registerToSuperclass (klass) {
  226. addElement((klass.superclass || nilAsClass).subclasses, klass);
  227. }
  228. function unregisterFromSuperclass (klass) {
  229. removeElement((klass.superclass || nilAsClass).subclasses, klass);
  230. }
  231. function metaSubclasses (metaclass) {
  232. return metaclass.instanceClass.subclasses
  233. .filter(function (each) {
  234. return !each.meta;
  235. })
  236. .map(function (each) {
  237. return each.a$cls;
  238. });
  239. }
  240. st.metaSubclasses = metaSubclasses;
  241. st.traverseClassTree = function (klass, fn) {
  242. var queue = [klass], sentinel = {};
  243. for (var i = 0; i < queue.length; ++i) {
  244. var item = queue[i];
  245. if (fn(item, sentinel) === sentinel) continue;
  246. var subclasses = item.meta ? metaSubclasses(item) : item.subclasses;
  247. queue.push.apply(queue, subclasses);
  248. }
  249. };
  250. /**
  251. * This function is used all over the compiled amber code.
  252. * It takes any value (JavaScript or Smalltalk)
  253. * and returns a proper Amber Smalltalk receiver.
  254. *
  255. * null or undefined -> nilAsReceiver,
  256. * object having Smalltalk signature -> unchanged,
  257. * otherwise wrapped foreign (JS) object
  258. */
  259. this.asReceiver = function (o) {
  260. if (o == null) return nilAsReceiver;
  261. else if (o.a$cls != null) return o;
  262. else return st.wrapJavaScript(o);
  263. };
  264. // TODO remove, .iVarNames backward compatibility
  265. this.__init__ = function () {
  266. brikz.classConstruction.iVarNamesCompat(SmalltalkBehavior);
  267. };
  268. }
  269. ClassConstructionBrik.deps = ["classModel", "behaviorals", "methods"];
  270. function ClassConstructionBrik (brikz, st) {
  271. var nilAsClass = brikz.classModel.nilAsClass;
  272. var newMetaclass = brikz.classModel.newMetaclass;
  273. var buildTraitOrClass = brikz.behaviorals.buildTraitOrClass;
  274. var setupMethods = brikz.methods.setupMethods;
  275. var removeTraitOrClass = brikz.behaviorals.removeTraitOrClass;
  276. declareEvent("slotsChanged");
  277. function setSlots (klass, slots) {
  278. slots.forEach(function (name) {
  279. if (!name.match(/^[a-zA-Z][a-zA-Z0-9]*$/))
  280. throw new Error("Wrong identifier name: " + name);
  281. });
  282. klass.slots = slots;
  283. emit.slotsChanged(klass);
  284. }
  285. st.setSlots = setSlots;
  286. // TODO remove, .iVarNames backward compatibility
  287. this.iVarNamesCompat = function (SmalltalkBehavior) {
  288. Object.defineProperty(SmalltalkBehavior.prototype, "iVarNames", {
  289. enumerable: true,
  290. configurable: true,
  291. get: function () {
  292. return this.slots;
  293. },
  294. set: function (instanceVariableNames) {
  295. setSlots(this, instanceVariableNames);
  296. }
  297. });
  298. };
  299. /* Smalltalk class creation. A class is an instance of an automatically
  300. created metaclass object. Newly created classes (not their metaclass)
  301. should be added to the system, see smalltalk.addClass().
  302. Superclass linking is *not* handled here, see api.initialize() */
  303. function classBuilder (className, superclass, category, fn) {
  304. var logicalSuperclass = superclass;
  305. if (superclass == null || superclass.a$nil) {
  306. superclass = nilAsClass;
  307. logicalSuperclass = null;
  308. }
  309. function klass () {
  310. var that = metaclass().instanceClass;
  311. that.superclass = logicalSuperclass;
  312. that.fn = fn || inherits(function () {
  313. }, superclass.fn);
  314. that.slots = [];
  315. that.name = className;
  316. that.category = category;
  317. that.subclasses = [];
  318. setupMethods(that);
  319. return that;
  320. }
  321. function metaclass () {
  322. var that = newMetaclass();
  323. that.superclass = superclass.a$cls;
  324. that.fn = inherits(function () {
  325. }, that.superclass.fn);
  326. that.slots = [];
  327. that.instanceClass = new that.fn();
  328. wireKlass(that);
  329. setupMethods(that);
  330. return that;
  331. }
  332. return {
  333. name: className,
  334. make: klass,
  335. updateExisting: function (klass) {
  336. if (logicalSuperclass == null && klass.superclass != null || logicalSuperclass != null && klass.superclass !== logicalSuperclass || fn != null && fn !== klass.fn)
  337. throw new Error("Incompatible change of class: " + klass.name);
  338. }
  339. };
  340. }
  341. function wireKlass (klass) {
  342. Object.defineProperty(klass.fn.prototype, "a$cls", {
  343. value: klass,
  344. enumerable: false, configurable: true, writable: true
  345. });
  346. }
  347. this.wireKlass = wireKlass;
  348. /* Add a class to the system, creating a new one if needed.
  349. A Package is lazily created if one with given name does not exist. */
  350. st.addClass = function (className, superclass, category) {
  351. // TODO remove, backward compatibility
  352. if (arguments[3]) {
  353. var added = st.addClass(className, superclass, arguments[3]);
  354. setSlots(added, category);
  355. return added;
  356. }
  357. // While subclassing nil is allowed, it might be an error, so
  358. // warn about it.
  359. if (typeof superclass === 'undefined' || superclass && superclass.a$nil) {
  360. console.warn('Compiling ' + className + ' as a subclass of `nil`. A dependency might be missing.');
  361. }
  362. return buildTraitOrClass(classBuilder(className, superclass, category, specialConstructors[className]));
  363. };
  364. st.removeClass = removeTraitOrClass;
  365. }
  366. /* Making smalltalk that can load */
  367. function configure (brikz) {
  368. brikz.traits = TraitsBrik;
  369. brikz.composition = MethodCompositionBrik;
  370. brikz.classModel = ClassModelBrik;
  371. brikz.classConstruction = ClassConstructionBrik;
  372. brikz();
  373. }
  374. return {configure: configure};
  375. }
  376. return LanguageFactory;
  377. });