1
0

kernel-language.js 17 KB

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