kernel-language.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. // TODO remove, .iVarNames backward compatibility
  256. this.__init__ = function () {
  257. brikz.classConstruction.iVarNamesCompat(SmalltalkBehavior);
  258. };
  259. }
  260. ClassConstructionBrik.deps = ["classModel", "behaviorals", "methods"];
  261. function ClassConstructionBrik (brikz, st) {
  262. var nilAsClass = brikz.classModel.nilAsClass;
  263. var newMetaclass = brikz.classModel.newMetaclass;
  264. var buildTraitOrClass = brikz.behaviorals.buildTraitOrClass;
  265. var setupMethods = brikz.methods.setupMethods;
  266. var removeTraitOrClass = brikz.behaviorals.removeTraitOrClass;
  267. declareEvent("slotsChanged");
  268. function setSlots (klass, slots) {
  269. slots.forEach(function (name) {
  270. if (!name.match(/^[a-zA-Z][a-zA-Z0-9]*$/))
  271. throw new Error("Wrong identifier name: " + name);
  272. });
  273. klass.slots = slots;
  274. emit.slotsChanged(klass);
  275. }
  276. st.setSlots = setSlots;
  277. // TODO remove, .iVarNames backward compatibility
  278. this.iVarNamesCompat = function (SmalltalkBehavior) {
  279. Object.defineProperty(SmalltalkBehavior.prototype, "iVarNames", {
  280. enumerable: true,
  281. configurable: true,
  282. get: function () {
  283. return this.slots;
  284. },
  285. set: function (instanceVariableNames) {
  286. setSlots(this, instanceVariableNames);
  287. }
  288. });
  289. };
  290. /* Smalltalk class creation. A class is an instance of an automatically
  291. created metaclass object. Newly created classes (not their metaclass)
  292. should be added to the system, see smalltalk.addClass().
  293. Superclass linking is *not* handled here, see api.initialize() */
  294. function classBuilder (className, superclass, category, fn) {
  295. var logicalSuperclass = superclass;
  296. if (superclass == null || superclass.a$nil) {
  297. superclass = nilAsClass;
  298. logicalSuperclass = null;
  299. }
  300. function klass () {
  301. var that = metaclass().instanceClass;
  302. that.superclass = logicalSuperclass;
  303. that.fn = fn || inherits(function () {
  304. }, superclass.fn);
  305. that.slots = [];
  306. that.name = className;
  307. that.category = category;
  308. that.subclasses = [];
  309. setupMethods(that);
  310. return that;
  311. }
  312. function metaclass () {
  313. var that = newMetaclass();
  314. that.superclass = superclass.a$cls;
  315. that.fn = inherits(function () {
  316. }, that.superclass.fn);
  317. that.slots = [];
  318. that.instanceClass = new that.fn();
  319. wireKlass(that);
  320. setupMethods(that);
  321. return that;
  322. }
  323. return {
  324. name: className,
  325. make: klass,
  326. updateExisting: function (klass) {
  327. if (logicalSuperclass == null && klass.superclass != null || logicalSuperclass != null && klass.superclass !== logicalSuperclass || fn != null && fn !== klass.fn)
  328. throw new Error("Incompatible change of class: " + klass.name);
  329. }
  330. };
  331. }
  332. function wireKlass (klass) {
  333. Object.defineProperty(klass.fn.prototype, "a$cls", {
  334. value: klass,
  335. enumerable: false, configurable: true, writable: true
  336. });
  337. }
  338. this.wireKlass = wireKlass;
  339. /* Add a class to the system, creating a new one if needed.
  340. A Package is lazily created if one with given name does not exist. */
  341. st.addClass = function (className, superclass, category) {
  342. // TODO remove, backward compatibility
  343. if (arguments[3]) {
  344. var added = st.addClass(className, superclass, arguments[3]);
  345. setSlots(added, category);
  346. return added;
  347. }
  348. // While subclassing nil is allowed, it might be an error, so
  349. // warn about it.
  350. if (typeof superclass === 'undefined' || superclass && superclass.a$nil) {
  351. console.warn('Compiling ' + className + ' as a subclass of `nil`. A dependency might be missing.');
  352. }
  353. return buildTraitOrClass(classBuilder(className, superclass, category, specialConstructors[className]));
  354. };
  355. st.removeClass = removeTraitOrClass;
  356. }
  357. /* Making smalltalk that can load */
  358. function configure (brikz) {
  359. brikz.traits = TraitsBrik;
  360. brikz.composition = MethodCompositionBrik;
  361. brikz.classModel = ClassModelBrik;
  362. brikz.classConstruction = ClassConstructionBrik;
  363. brikz();
  364. }
  365. return {configure: configure};
  366. }
  367. return LanguageFactory;
  368. });