kernel-language.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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}
  207. };
  208. this.bootstrapHierarchy = function (realClass) {
  209. nilAsClass.a$cls = realClass;
  210. nilAsClass.subclasses.forEach(function (each) {
  211. each.a$cls.superclass = realClass;
  212. registerToSuperclass(each.a$cls);
  213. });
  214. };
  215. function registerToSuperclass (klass) {
  216. addElement((klass.superclass || nilAsClass).subclasses, klass);
  217. }
  218. function unregisterFromSuperclass (klass) {
  219. removeElement((klass.superclass || nilAsClass).subclasses, klass);
  220. }
  221. function metaSubclasses (metaclass) {
  222. return metaclass.instanceClass.subclasses
  223. .filter(function (each) {
  224. return !each.meta;
  225. })
  226. .map(function (each) {
  227. return each.a$cls;
  228. });
  229. }
  230. st.metaSubclasses = metaSubclasses;
  231. st.traverseClassTree = function (klass, fn) {
  232. var queue = [klass], sentinel = {};
  233. for (var i = 0; i < queue.length; ++i) {
  234. var item = queue[i];
  235. if (fn(item, sentinel) === sentinel) continue;
  236. var subclasses = item.meta ? metaSubclasses(item) : item.subclasses;
  237. queue.push.apply(queue, subclasses);
  238. }
  239. };
  240. /**
  241. * This function is used all over the compiled amber code.
  242. * It takes any value (JavaScript or Smalltalk)
  243. * and returns a proper Amber Smalltalk receiver.
  244. *
  245. * null or undefined -> nilAsReceiver,
  246. * object having Smalltalk signature -> unchanged,
  247. * otherwise wrapped foreign (JS) object
  248. */
  249. this.asReceiver = function (o) {
  250. if (o == null) return nilAsReceiver;
  251. else if (o.a$cls != null) return o;
  252. else return st.wrapJavaScript(o);
  253. };
  254. // TODO remove, .iVarNames backward compatibility
  255. this.__init__ = function () {
  256. brikz.classConstruction.iVarNamesCompat(SmalltalkBehavior);
  257. };
  258. }
  259. ClassConstructionBrik.deps = ["classModel", "behaviorals", "methods"];
  260. function ClassConstructionBrik (brikz, st) {
  261. var nilAsClass = brikz.classModel.nilAsClass;
  262. var newMetaclass = brikz.classModel.newMetaclass;
  263. var buildTraitOrClass = brikz.behaviorals.buildTraitOrClass;
  264. var setupMethods = brikz.methods.setupMethods;
  265. var removeTraitOrClass = brikz.behaviorals.removeTraitOrClass;
  266. declareEvent("slotsChanged");
  267. function setSlots (klass, slots) {
  268. slots.forEach(function (name) {
  269. if (!name.match(/^[a-zA-Z][a-zA-Z0-9]*$/))
  270. throw new Error("Wrong identifier name: " + name);
  271. });
  272. klass.slots = slots;
  273. emit.slotsChanged(klass);
  274. }
  275. st.setSlots = setSlots;
  276. // TODO remove, .iVarNames backward compatibility
  277. this.iVarNamesCompat = function (SmalltalkBehavior) {
  278. Object.defineProperty(SmalltalkBehavior.prototype, "iVarNames", {
  279. enumerable: true,
  280. configurable: true,
  281. get: function () {
  282. return this.slots;
  283. },
  284. set: function (instanceVariableNames) {
  285. setSlots(this, instanceVariableNames);
  286. }
  287. });
  288. };
  289. /* Smalltalk class creation. A class is an instance of an automatically
  290. created metaclass object. Newly created classes (not their metaclass)
  291. should be added to the system, see smalltalk.addClass().
  292. Superclass linking is *not* handled here, see api.initialize() */
  293. function classBuilder (className, superclass, category, fn) {
  294. var logicalSuperclass = superclass;
  295. if (superclass == null || superclass.a$nil) {
  296. superclass = nilAsClass;
  297. logicalSuperclass = null;
  298. }
  299. function klass () {
  300. var that = metaclass().instanceClass;
  301. that.superclass = logicalSuperclass;
  302. that.fn = fn || inherits(function () {
  303. }, superclass.fn);
  304. that.slots = [];
  305. that.name = className;
  306. that.category = category;
  307. that.subclasses = [];
  308. setupMethods(that);
  309. return that;
  310. }
  311. function metaclass () {
  312. var that = newMetaclass();
  313. that.superclass = superclass.a$cls;
  314. that.fn = inherits(function () {
  315. }, that.superclass.fn);
  316. that.slots = [];
  317. that.instanceClass = new that.fn();
  318. wireKlass(that);
  319. setupMethods(that);
  320. return that;
  321. }
  322. return {
  323. name: className,
  324. make: klass,
  325. updateExisting: function (klass) {
  326. if (logicalSuperclass == null && klass.superclass != null || logicalSuperclass != null && klass.superclass !== logicalSuperclass || fn != null && fn !== klass.fn)
  327. throw new Error("Incompatible change of class: " + klass.name);
  328. }
  329. };
  330. }
  331. function wireKlass (klass) {
  332. Object.defineProperty(klass.fn.prototype, "a$cls", {
  333. value: klass,
  334. enumerable: false, configurable: true, writable: true
  335. });
  336. }
  337. this.wireKlass = wireKlass;
  338. /* Add a class to the system, creating a new one if needed.
  339. A Package is lazily created if one with given name does not exist. */
  340. st.addClass = function (className, superclass, category) {
  341. // TODO remove, backward compatibility
  342. if (arguments[3]) {
  343. var added = st.addClass(className, superclass, arguments[3]);
  344. setSlots(added, category);
  345. return added;
  346. }
  347. // While subclassing nil is allowed, it might be an error, so
  348. // warn about it.
  349. if (typeof superclass === 'undefined' || superclass && superclass.a$nil) {
  350. console.warn('Compiling ' + className + ' as a subclass of `nil`. A dependency might be missing.');
  351. }
  352. return buildTraitOrClass(classBuilder(className, superclass, category, specialConstructors[className]));
  353. };
  354. st.removeClass = removeTraitOrClass;
  355. }
  356. /* Making smalltalk that can load */
  357. function configure (brikz) {
  358. brikz.traits = TraitsBrik;
  359. brikz.composition = MethodCompositionBrik;
  360. brikz.classModel = ClassModelBrik;
  361. brikz.classConstruction = ClassConstructionBrik;
  362. brikz();
  363. }
  364. return {configure: configure};
  365. }
  366. return LanguageFactory;
  367. });