libmt.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /* This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. * Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. * See COPYING.lesser and README.md in the root of this project for full details
  4. */
  5. const _utils = require('./utils');
  6. /* eslint-disable no-inner-declarations */
  7. module.exports = {
  8. /* apply transformation T to specified model
  9. TBI:: this method only supports transforming class diagrams to ER diagrams
  10. and does so programmatically (vs. locating an appropriate [chain of]
  11. model transformations and running them) */
  12. 'transform' :
  13. function(_model,T)
  14. {
  15. if (!Array.prototype.find) {
  16. Array.prototype.find = function(predicate) {
  17. if (this == null) {
  18. throw new TypeError('Array.prototype.find called on null or undefined');
  19. }
  20. if (typeof predicate !== 'function') {
  21. throw new TypeError('predicate must be a function');
  22. }
  23. var list = Object(this);
  24. var length = list.length >>> 0;
  25. var thisArg = arguments[1];
  26. var value;
  27. for (var i = 0; i < length; i++) {
  28. value = list[i];
  29. if (predicate.call(thisArg, value, i, list)) {
  30. return value;
  31. }
  32. }
  33. return undefined;
  34. };
  35. }
  36. var model = _utils.jsonp(_model),
  37. new_model = _utils.jsonp(_model),
  38. SCD = '/Formalisms/__LanguageSyntax__/SimpleClassDiagram/SimpleClassDiagram',
  39. ER = '/Formalisms/__LanguageSyntax__/EntityRelationship/EntityRelationship';
  40. if( T == 'SimpleClassDiagram-2-EntityRelationship' )
  41. {
  42. /* 1 map each type to all of its ancestors
  43. 2 flatten ancestor contents into their children + 'reroute' associations
  44. 3 make new_model conform to ER
  45. 4 append type-to-parentType mapping (needed for MT subtype matching) */
  46. function copyAttributes(parent_id, child_id) {
  47. new_model.nodes[child_id]['attributes']['value'] =
  48. new_model.nodes[child_id]['attributes']['value'].concat(
  49. new_model.nodes[parent_id]['attributes']['value'].filter(
  50. function(attr) {
  51. return !new_model.nodes[child_id]['attributes']['value'].find(
  52. function(el) {return el['name'] == attr['name'];}
  53. );
  54. }
  55. )
  56. );
  57. new_model.nodes[child_id]['constraints']['value'] =
  58. new_model.nodes[child_id]['constraints']['value'].concat(
  59. new_model.nodes[parent_id]['constraints']['value'].filter(
  60. function(constr) {
  61. return !new_model.nodes[child_id]['constraints']['value'].find(
  62. function(el) {return el['name'] == constr['name'];}
  63. );
  64. }
  65. )
  66. );
  67. new_model.nodes[child_id]['actions']['value'] =
  68. new_model.nodes[child_id]['actions']['value'].concat(
  69. new_model.nodes[parent_id]['actions']['value'].filter(
  70. function(act) {
  71. return !new_model.nodes[child_id]['actions']['value'].find(
  72. function(el) {return el['name'] == act['name'];}
  73. );
  74. }
  75. )
  76. );
  77. new_model.nodes[child_id]['cardinalities']['value'] =
  78. new_model.nodes[child_id]['cardinalities']['value'].concat(
  79. new_model.nodes[parent_id]['cardinalities']['value'].filter(
  80. function(card) {
  81. return !new_model.nodes[child_id]['cardinalities']['value'].find(
  82. function(el) {return el['dir'] == card['dir'] && el['type'] == card['type'];}
  83. );
  84. }
  85. )
  86. );
  87. }
  88. function findAncestors(ids)
  89. {
  90. var inheritances = [];
  91. model.edges.forEach(
  92. function(edge)
  93. {
  94. if( _utils.contains(ids,edge['src']) &&
  95. model.nodes[edge['dest']]['$type'] == SCD+'/Inheritance' )
  96. inheritances.push(edge['dest']);
  97. });
  98. if( inheritances.length == 0 ) {
  99. return ids;
  100. }
  101. var parents = [];
  102. model.edges.forEach(
  103. function(edge)
  104. {
  105. if( _utils.contains(inheritances,edge['src']) )
  106. parents.push(edge['dest']);
  107. });
  108. return ids.concat(findAncestors(parents));
  109. }
  110. var ids2ancestors = {};
  111. for( var id in model.nodes )
  112. {
  113. /* 1 */
  114. var ids = findAncestors([id]);
  115. ids.reverse(); // oldest first
  116. var idx = 1;
  117. while (idx < ids.length) {
  118. copyAttributes(ids[idx-1], ids[idx]);
  119. idx++;
  120. }
  121. ids2ancestors[id] = ids;
  122. ids2ancestors[id].splice(-1);
  123. /* 2 */
  124. /* a) apply attributes, constraints, actions and cardinalities inheritance to id
  125. b) update cardinalities of Associations who connect to parent + add edges between Associations
  126. and children... this effectively does association inheritance */
  127. ids2ancestors[id].forEach(
  128. function(a)
  129. {
  130. var ancestorType = model.nodes[a]['name']['value'],
  131. idType = model.nodes[id]['name']['value'];
  132. model.edges.forEach(
  133. function(edge)
  134. {
  135. if( edge['src'] == a || edge['dest'] == a )
  136. {
  137. var ancestorIsSrc = (edge['src'] == a),
  138. assoc = (ancestorIsSrc ? edge['dest'] : edge['src']);
  139. if( model.nodes[assoc]['$type'] != SCD+'/Association' )
  140. return;
  141. for( var i in model.nodes[assoc]['cardinalities']['value'] )
  142. {
  143. var card = model.nodes[assoc]['cardinalities']['value'][i];
  144. if( card['type'] == ancestorType && card['dir'] == (ancestorIsSrc ? 'out' : 'in') )
  145. {
  146. var new_card = _utils.clone(card);
  147. new_card['type'] = idType;
  148. new_model.nodes[assoc]['cardinalities']['value'].push(new_card);
  149. }
  150. }
  151. new_model.edges.push(
  152. (ancestorIsSrc ? {'src':id,'dest':assoc} : {'src':assoc,'dest':id}) );
  153. }
  154. });
  155. });
  156. }
  157. /* 3 */
  158. /* due to extreme similarity between SCD and ER, we only need to
  159. a) update $type attributes
  160. special case: make abstract classes uninstantiable
  161. special case: remove inheritances
  162. b) update new_model.metamodels */
  163. for( var id in new_model.nodes )
  164. {
  165. if( new_model.nodes[id]['$type'] == SCD+'/Class' )
  166. {
  167. new_model.nodes[id]['$type'] = ER+'/Entity';
  168. if( new_model.nodes[id]['abstract']['value'] )
  169. {
  170. new_model.nodes[id]['constraints']['value'].push(
  171. {'name':'noAbstractInstances',
  172. 'event':'pre-create',
  173. 'code':'false'});
  174. }
  175. }
  176. else if( new_model.nodes[id]['$type'] == SCD+'/Association' )
  177. new_model.nodes[id]['$type'] = ER+'/Relationship';
  178. else if( new_model.nodes[id]['$type'] == SCD+'/GlobalConstraint' )
  179. new_model.nodes[id]['$type'] = ER+'/GlobalConstraint';
  180. else if( new_model.nodes[id]['$type'] == SCD+'/GlobalAction' )
  181. new_model.nodes[id]['$type'] = ER+'/GlobalAction';
  182. else if( new_model.nodes[id]['$type'] == SCD+'/Inheritance' )
  183. {
  184. /* special case: inheritance
  185. a) remove all edges pertaining to it
  186. b) remove it */
  187. new_model.edges = new_model.edges.filter(
  188. function(edge) {return edge['src'] != id && edge['dest'] != id;});
  189. delete new_model.nodes[id];
  190. }
  191. }
  192. new_model.metamodels = [ER];
  193. /* 4 */
  194. var types2parentTypes = {};
  195. for( var id in new_model.nodes )
  196. {
  197. var type = new_model.nodes[id]['name']['value'];
  198. if( types2parentTypes[type] == undefined )
  199. {
  200. types2parentTypes[type] = [];
  201. ids2ancestors[id].forEach(
  202. function(a)
  203. {
  204. types2parentTypes[type].push(new_model.nodes[a]['name']['value']);
  205. });
  206. }
  207. }
  208. new_model['types2parentTypes'] = types2parentTypes;
  209. /* return transformed model... note the little hack here... the reason for this is that pushing
  210. the 'same' attribute/constraint/action/cardiniality *objects* during the inheritance process
  211. causes problems when these are later edited (e.g., extended with targetType in compileToMM)
  212. since they all point to each other and changing one changes them all... */
  213. return _utils.clone(new_model);
  214. }
  215. else
  216. return {'$err':'unknown transformation :: '+T};
  217. },
  218. /* RAMify an AS metamodel and associated CS metamodel(s)
  219. 1. RELAX
  220. a) alter all constraints such that they are always satisfied (includes
  221. constraints that prevent instantiation of abstract types) + remember
  222. abstract types (for step 2diii)
  223. b) alter all actions such that they have no effect
  224. c) reduce all minimum multiplicities to 0
  225. 2. AUGMENT & MODIFY
  226. a) setup pattern types, constraints, actions, cardinalities, etc.
  227. b) replace types, constraints, etc. by results of steps a)
  228. c) insert post-create action that sets newly created, non-copied nodes'
  229. __pLabels to non-taken values
  230. d) alter each CS metamodel (i.e., icon definitions)
  231. i. use pattern type names
  232. ii. remove parsing and mapping functions (because pattern attribute
  233. values are code, as opposed to their 'original' types)
  234. iii. create basic icons for abstract types
  235. iv. add a Text VisualObject to show/edit the __pLabel attribute to
  236. every icon */
  237. 'ramify' :
  238. function(asmm,csmms)
  239. {
  240. var abstractTypes = [];
  241. for( var i in asmm.constraints )
  242. {
  243. if( asmm.constraints[i]['name'] == 'noAbstractInstances' )
  244. abstractTypes.push(asmm.constraints[i]['targetType']);
  245. asmm.constraints[i]['code'] =
  246. '/* comment next line to enable this constraint */\n'+
  247. 'throw "IgnoredConstraint"\n'+asmm.constraints[i]['code'];
  248. }
  249. for( var i in asmm.actions )
  250. asmm.actions[i]['code'] =
  251. '/* comment next line to enable this action */\n'+
  252. 'throw "IgnoredConstraint"\n'+asmm.actions[i]['code'];
  253. for( var t in asmm.cardinalities )
  254. for( var i in asmm.cardinalities[t] )
  255. asmm.cardinalities[t][i]['min'] = 0;
  256. var patternTypes = {},
  257. patternActions = [],
  258. patternCards = {},
  259. patternLegalConns = {},
  260. patternConnTypes = {},
  261. patternT2PT = {};
  262. for( var t in asmm.types )
  263. {
  264. patternTypes['__p'+t] =
  265. [{'name':'__pLabel', 'type':'string', 'default':''},
  266. {'name':'__pPivotIn', 'type':'string', 'default':''}, /* hergin motif-integration */
  267. {'name':'__pPivotOut', 'type':'string', 'default':''}, /* hergin motif-integration */
  268. {'name':'__pMatchSubtypes', 'type':'boolean', 'default':true}];
  269. for( var i in asmm.types[t] )
  270. patternTypes['__p'+t].push(
  271. {'name':asmm.types[t][i]['name'],
  272. 'type':'code',
  273. 'default':
  274. '"[PYTHON]"\n"Example:\t result = True"\n"Example:\t result = getAttr()"\n\n'+
  275. '"[JAVASCRIPT]"\n"Example:\t true"\n"Example:\t getAttr()"'});
  276. }
  277. for( var i in asmm.actions )
  278. {
  279. var action = asmm.actions[i];
  280. patternActions.push(_utils.clone(action));
  281. patternActions[patternActions.length-1]['targetType'] = '__p'+action['targetType'];
  282. }
  283. for( var t in asmm.cardinalities )
  284. {
  285. patternCards['__p'+t] = [];
  286. for( var i in asmm.cardinalities[t] )
  287. {
  288. var card = asmm.cardinalities[t][i];
  289. patternCards['__p'+t].push(_utils.clone(card));
  290. patternCards['__p'+t][i]['type'] = '__p'+card['type'];
  291. }
  292. }
  293. for( var t1 in asmm.legalConnections )
  294. {
  295. patternLegalConns['__p'+t1] = {};
  296. for( var t2 in asmm.legalConnections[t1] )
  297. {
  298. patternLegalConns['__p'+t1]['__p'+t2] = [];
  299. for( var i in asmm.legalConnections[t1][t2] )
  300. patternLegalConns['__p'+t1]['__p'+t2].push(
  301. '__p'+asmm.legalConnections[t1][t2][i]);
  302. }
  303. }
  304. for( var t in asmm.connectorTypes )
  305. patternConnTypes['__p'+t] = asmm.connectorTypes[t];
  306. for( var t in asmm.types2parentTypes )
  307. {
  308. patternT2PT['__p'+t] = [];
  309. for( var i in asmm.types2parentTypes[t] )
  310. patternT2PT['__p'+t].push('__p'+asmm.types2parentTypes[t][i]);
  311. }
  312. asmm.types = patternTypes;
  313. asmm.actions = patternActions;
  314. asmm.cardinalities = patternCards;
  315. asmm.legalConnections = patternLegalConns;
  316. asmm.connectorTypes = patternConnTypes;
  317. asmm.types2parentTypes = patternT2PT;
  318. patternActions.push(
  319. {'name': 'distinctPLabels',
  320. 'event': 'post-create',
  321. 'code': 'if( getAttr("__pLabel") == "" )\n'+
  322. '{\n'+
  323. ' var pLabels = getAllNodes().\n'+
  324. ' filter( function(n) {return hasAttr("__pLabel",n);} ).\n'+
  325. ' map( function(n) {return getAttr("__pLabel",n);} ),\n'+
  326. ' i = "0";\n'+
  327. '\n'+
  328. ' while( _utils.contains(pLabels,i) )\n'+
  329. ' i = String(parseInt(i)+1);\n'+
  330. ' setAttr("__pLabel",i);\n'+
  331. '}',
  332. 'targetType': '*'});
  333. function addPLabelTextVisualObject(nodes)
  334. {
  335. nodes['__pLabelText'] = {"position": {"type": "list<double>", "value": [0,0]},
  336. "orientation": {"type": "double", "value": 0},
  337. "scale": {"type": "list<double>", "value": [1,1]},
  338. "textContent": {"type": "string", "value": "#"},
  339. "style": {"type": "map<string,string>", "value": {"stroke": "#6000ff",
  340. "fill": "#6000ff",
  341. "font-size": "15px",
  342. "opacity": "1"}},
  343. "mapper": {"type": "code", "value": "({'textContent':getAttr('__pLabel')})"},
  344. "parser": {"type": "code", "value": "({'__pLabel':getAttr('textContent')})"},
  345. "$type": "/Formalisms/__LanguageSyntax__/ConcreteSyntax/ConcreteSyntax/Text"};
  346. }
  347. var NO_MAPPERS_PARSERS = '/* mapping and parsing code is disabled by default because pattern attribute values are code */';
  348. for( var csmm in csmms )
  349. {
  350. var patternTypes = {},
  351. patternCards = {},
  352. patternT2PT = {};
  353. csmms[csmm] = _utils.jsonp(csmms[csmm]);
  354. for( type in csmms[csmm].types )
  355. {
  356. var contents = undefined;
  357. patternTypes['__p'+type] = _utils.clone(csmms[csmm].types[type]);
  358. patternCards['__p'+type] = [];
  359. patternT2PT['__p'+type] = [];
  360. patternTypes['__p'+type].forEach(
  361. function(attr)
  362. {
  363. if( attr['name'] == '$contents' )
  364. contents = attr;
  365. else if( attr['name'] == 'parser' || attr['name'] == 'mapper' )
  366. attr['default'] = NO_MAPPERS_PARSERS;
  367. });
  368. for( id in contents['default']['nodes'] )
  369. for( attr in contents['default']['nodes'][id] )
  370. if( attr == 'parser' || attr == 'mapper' )
  371. contents['default']['nodes'][id][attr]['value'] = NO_MAPPERS_PARSERS;
  372. addPLabelTextVisualObject(contents['default']['nodes']);
  373. }
  374. abstractTypes.forEach(
  375. function(type)
  376. {
  377. patternCards['__p'+type+'Icon'] = [];
  378. patternT2PT['__p'+type+'Icon'] = [];
  379. patternTypes['__p'+type+'Icon'] = [{"name": "typename", "type": "string", "default": '__p'+type+'Icon'},
  380. {"name": "position", "type": "list<double>", "default": [0,0]},
  381. {"name": "orientation", "type": "double", "default": 0},
  382. {"name": "scale", "type": "list<double>", "default": [1,1]},
  383. {"name": "mapper", "type": "code", "default": ''},
  384. {"name": "parser", "type": "code", "default": ''},
  385. {"name": "$contents", "type": "map<string,*>", "default": {
  386. "nodes": {
  387. "text": {
  388. "textContent": {"type": "string", "value": '__p'+type+'Icon'},
  389. "style": {"type": "map<string,string>", "value": {"stroke": "#000000",
  390. "stroke-dasharray": "",
  391. "fill": "#000000",
  392. "fill-opacity": "1",
  393. "font-size": "13px"}},
  394. "mapper": {"type": "code", "value": ""},
  395. "parser": {"type": "code", "value": ""},
  396. "$type": "/Formalisms/__LanguageSyntax__/ConcreteSyntax/ConcreteSyntax/Text",
  397. "position": {"type": "list<double>", "value": [10,76]},
  398. "orientation": {"type": "double", "value": 0},
  399. "scale": {"type": "list<double>", "value": [1,1]}},
  400. "rect": {
  401. "width": {"type": "double", "value": 75},
  402. "height": {"type": "double", "value": 75},
  403. "cornerRadius": {"type": "double", "value": 15},
  404. "style": {"type": "map<string,string>", "value": {"stroke": "#000000",
  405. "fill": "#ffffff",
  406. "fill-opacity": 0.75}},
  407. "mapper": {"type": "code", "value": ""},
  408. "parser": {"type": "code", "value": ""},
  409. "$type": "/Formalisms/__LanguageSyntax__/ConcreteSyntax/ConcreteSyntax/Rectangle",
  410. "position": {"type": "list<double>", "value": [0,0]},
  411. "orientation": {"type": "double", "value": 0},
  412. "scale": {"type": "list<double>", "value": [1,1]}},
  413. "textBelowRect": {
  414. "distance": {"type": "double", "value": 10},
  415. "alignment": {"type": "ENUM(\"right\",\"left\",\"center\")", "value": "center"},
  416. "$type": "/Formalisms/__LanguageSyntax__/ConcreteSyntax/ConcreteSyntax/Below",
  417. "position": {"type": "list<double>", "value": [5,38]},
  418. "orientation": {"type": "double", "value": 0},
  419. "scale": {"type": "list<double>", "value": [1,1]},
  420. "link-style": {"type": "map<string,string>", "value": {"stroke": "#00ff00",
  421. "stroke-dasharray": "",
  422. "stroke-opacity": 1,
  423. "arrow-start": "none",
  424. "arrow-end": "classic-wide-long"}}}},
  425. "edges": [{"src": "text", "dest": "textBelowRect"},
  426. {"src": "textBelowRect", "dest": "rect"}]}},
  427. {"name": "$asuri", "type": "string", "default": "-1"}];
  428. addPLabelTextVisualObject(patternTypes['__p'+type+'Icon'][6]['default']['nodes']);
  429. });
  430. csmms[csmm].types = patternTypes;
  431. csmms[csmm].cardinalities = patternCards;
  432. csmms[csmm].types2parentTypes = patternT2PT;
  433. }
  434. return {'asmm':asmm,'csmms':csmms};
  435. }
  436. };