kernel-language.js 18 KB

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