forked from mdeforall/atompm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mmmk.js
1946 lines (1712 loc) · 62.9 KB
/
mmmk.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
* Copyright 2011 by the AToMPM team and licensed under the LGPL
* See COPYING.lesser and README.md in the root of this project for full details
*/
/* NOTES:
atom3 supported pre/post actions and constraints for the 'SAVE' EVENT...
this never really made any sense (e.g., the user could be prevented from
saving and, technically, the effects of post-actions were never saved)...
atom3 supported 'save' events as a hack to enable forcing mm validation...
in atompm, such validation is carried out by _mmmk.validateModel (which
clients can 'call') and thus, we do no support 'save' events... */
const _utils = require('./utils');
const _util = require("util");
const _mt = require("./libmt");
const _styleinfo = require('./styleinfo');
module.exports = {
/********************************* GLOBALS *********************************/
'metamodels':{},
'model':{'nodes':{},'edges':[],'metamodels':[]},
'name':'',
'next_id':0,
/********************************* ENV SETUP *******************************/
/* produce a bundle of internal state variables sufficient to fully clone
this instance
OR
use a provided bundle to overwrite this instance's internal state */
'clone' :
function(clone)
{
if( clone )
{
this.metamodels = clone.metamodels;
this.model = clone.model;
this.name = clone.name;
this.next_id = clone.next_id;
this.journal = clone.journal;
this.journalIndex = clone.journalIndex;
this.undoredoJournal = clone.undoredoJournal;
}
else
return _utils.clone(
{'metamodels': this.metamodels,
'model': this.model,
'name': this.name,
'next_id': this.next_id,
'journal': this.journal,
'journalIndex': this.journalIndex,
'undoredoJournal': this.undoredoJournal});
},
/* load a model into this.model
0. create step-checkpoint
1. make sure all required metamodels are loaded
2. if 'insert' is specified,
a) append 'model' to this.model (via __resetm__)
2. otherwise, load 'model' into this.model and 'name' into this.name
(via __resetm__) */
'loadModel' :
function(name,model,insert)
{
this.__setStepCheckpoint();
var new_model = eval('('+ model +')');
for( var i in new_model.metamodels )
if( this.metamodels[new_model.metamodels[i]] == undefined )
return {'$err':'metamodel not loaded :: '+new_model.metamodels[i]};
this.__resetm__(name,model,insert);
return {'changelog':this.__changelog()};
},
/* load a metamodel
0. create a step-checkpoint
1. load metamodel into this.model.metamodels and this.metamodels (via
__loadmm__) */
'loadMetamodel' :
function(name,mm)
{
this.__setStepCheckpoint();
this.__loadmm__(name,mm);
return {'changelog':this.__changelog()};
},
/* unload a metamodel and delete all entities from that metamodel
0. create a step-checkpoint
1. deletes nodes from specified metamodel
2. delete edges where deleted nodes appear
3. remove metamodel from this.model.metamodels and this.metamodels
(via __dumpmm__) */
'unloadMetamodel' :
function(name)
{
this.__setStepCheckpoint();
for( var i=0; i<this.model.edges.length; i++ )
{
var edge = this.model.edges[i];
if( this.__getMetamodel(this.model.nodes[edge['src']]['$type']) == name ||
this.__getMetamodel(this.model.nodes[edge['dest']]['$type']) == name )
this.__rmedge__(i--);
}
for( var id in this.model.nodes )
if( this.__getMetamodel(this.model.nodes[id]['$type']) == name )
this.__rmnode__(id);
this.__dumpmm__(name);
return {'changelog':this.__changelog()};
},
/******************************** MODEL CRUD *******************************/
/* wraps crud operations with generic boilerplate
0. setup next_type hack : the next_type variable is used to carry the type
of the to-be-created node for the special case of pre-create handlers
because their target nodes aren't yet in this.model.nodes
1. create a checkpoint (any failure along the way causes checkpoint
restore)
2. run all applicable pre-events constraints and actions
3. perform the specified crud operation
4. run all applicable post-events actions and constraints
5. clear unused checkpoint */
'__crudOp' :
function(metamodel,events,eventTargets,op,args)
{
if( this.metamodels[metamodel] == undefined )
return {'$err':'metamodel not loaded :: '+metamodel};
if( _utils.contains(events,'create') )
this.next_type = args.fulltype || args.connectorType;
this.__checkpoint();
var pre_events = events.slice(0).map(function(ev) {return 'pre-'+ev;}),
post_events = events.slice(0).map(function(ev) {return 'post-'+ev;});
if( (err = this.__runEventHandlers(this.metamodels[metamodel]['constraints'], pre_events, eventTargets, 'constraint')) ||
(err = this.__runEventHandlers(this.metamodels[metamodel]['actions'], pre_events, eventTargets, 'action')) ||
(err = this[op](args)) ||
(err = this.__runEventHandlers(this.metamodels[metamodel]['actions'], post_events, eventTargets, 'action')) ||
(err = this.__runEventHandlers(this.metamodels[metamodel]['constraints'], post_events, eventTargets, 'constraint')) )
{
this.__restoreCheckpoint();
return err;
}
this.__clearCheckpoint();
},
/* connect specified nodes with instance of connectorType
__connectNN: (connect 2 nodes)
1. run pre-connect on end nodes
2. run __create to create instance and connect it to end nodes
3. run post-connect on end nodes
__connectCN: (connect 1 node and 1 connector)
1. add an appropriate edge to this.model.edges
connect:
0. create a step-checkpoint
1. verify validity of requested connection (i.e., connection is legal
and max cardinalities haven't been reached)
2. if one of the nodes is a connector
a) run pre-connect on end nodes
b) create appropriate new edge between them (via __connectCN)
c) run post-connect on end nodes
2. if both nodes are non-connectors
a) run pre-create on connectorType
b) create connectorType instance and connect it to end nodes (via
__connectNN)
c) run post-create on connectorType
3. return err or (new or existing) connector's id */
'__connectNN' :
function(args/*id1,id2,connectorType,attrs*/)
{
return this.__crudOp(
this.__getMetamodel(args.connectorType),
['connect'],
[args.id1,args.id2],
'__create',
{'fulltype':args.connectorType,
'id1':args.id1,
'id2':args.id2,
'attrs':args.attrs});
},
'__connectCN' :
function(args/*id1,id2,connectorId*/)
{
this.__mkedge__(args.id1,args.id2);
},
'connect' :
function(id1,id2,connectorType,attrs)
{
this.__setStepCheckpoint();
var metamodel = this.__getMetamodel(connectorType),
t1 = this.__getType(this.model.nodes[id1]['$type']),
t2 = this.__getType(this.model.nodes[id2]['$type']),
tc = this.__getType(connectorType),
into = (t1 == tc ? t2 : tc),
from = (t2 == tc ? t1 : tc),
card_into = undefined,
card_from = undefined,
num_id1to = 0,
num_toid2 = 0,
self = this;
[t1,'$*','__p$*'].some(
function(t)
{
for( var i in self.metamodels[metamodel]['cardinalities'][t] )
{
var cardinality = self.metamodels[metamodel]['cardinalities'][t][i];
if( cardinality['type'] == into && cardinality['dir'] == 'out' )
{
card_into = cardinality;
return true;
}
}
});
[t2,'$*','__p$*'].some(
function(t)
{
for( var i in self.metamodels[metamodel]['cardinalities'][t] )
{
var cardinality = self.metamodels[metamodel]['cardinalities'][t][i];
if( cardinality['type'] == from && cardinality['dir'] == 'in' )
{
card_from = cardinality;
return true;
}
}
});
if( card_into == undefined || card_from == undefined )
return {'$err':'can not connect types '+t1+' and '+t2};
else if( card_into['max'] == 0 )
return {'$err':'maximum outbound multiplicity reached for '+t1+' ('+id1+') and type '+into};
else if( card_from['max'] == 0 )
return {'$err':'maximum inbound multiplicity reached for '+t2+' ('+id2+') and type '+from};
for( var i in this.model.edges )
{
var edge = this.model.edges[i];
if( edge['src'] == id1 &&
this.__getType(this.model.nodes[edge['dest']]['$type']) == into &&
++num_id1to >= card_into['max'] )
return {'$err':'maximum outbound multiplicity reached for '+t1+' ('+id1+') and type '+into};
if( edge['dest'] == id2 &&
this.__getType(this.model.nodes[edge['src']]['$type']) == from &&
++num_toid2 >= card_from['max'] )
return {'$err':'maximum inbound multiplicity reached for '+t2+' ('+id2+') and type '+from};
}
if( t1 == tc || t2 == tc )
{
var connectorId = (t1 == tc ? id1 : id2),
err = this.__crudOp(
metamodel,
['connect'],
[id1,id2],
'__connectCN',
{'id1':id1,
'id2':id2,
'connectorId':connectorId});
return err ||
{'id':connectorId,
'changelog':this.__changelog()};
}
else
{
var err = this.__crudOp(
metamodel,
['create'],
[this.next_id],
'__connectNN',
{'id1':id1,
'id2':id2,
'connectorType':connectorType,
'attrs':attrs});
return err ||
{'id':this.next_id++,
'changelog':this.__changelog()};
}
},
/* create an instance of fulltype
__create:
1. create [default] instance using metamodel [and possibly specified
attrs] + init $type
2. add to current model nodes
[3. if fulltype is a connectorType, create edges between node id1
and new instance and between new instance and node id2
create:
0. create a step-checkpoint
1. wrap __create in crudOp
2. return err or new instance id */
'__create' :
function(args/*fulltype,attrs,[,id1,id2]*/)
{
var metamodel = this.__getMetamodel(args.fulltype),
type = this.__getType(args.fulltype),
typeAttrs = this.metamodels[metamodel]['types'][type],
new_node = {};
if( typeAttrs == undefined )
return {'$err':'can not create instance of unknown type :: '+args.fulltype};
typeAttrs.forEach(
function(attr)
{
var val = (args.attrs && attr['name'] in args.attrs ?
args.attrs[attr['name']] :
attr['default']);
new_node[attr['name']] =
{'type':attr['type'],
'value':(typeof attr['default'] == 'object' ?
_utils.clone(val) :
val)};
});
new_node['$type'] = args.fulltype;
this.__mknode__(this.next_id,new_node);
if( args.id1 != undefined )
{
this.__mkedge__(args.id1,String(this.next_id));
this.__mkedge__(String(this.next_id),args.id2);
}
},
'create' :
function(fulltype,attrs)
{
this.__setStepCheckpoint();
var err = this.__crudOp(
this.__getMetamodel(fulltype),
['create'],
[this.next_id],
'__create',
{'fulltype':fulltype,
'attrs':attrs});
return err ||
{'id':this.next_id++,
'changelog':this.__changelog()};
},
/* delete the specified node (and appropriate edges and/or connectors)
__delete:
1. determine specified node's neighbors
2. if specified node is a connector (neighbors are non-connectors),
a) run pre-disconnect constraints and actions and on its neighbors
b) delete it and all appropriate edges (via __deleteConnector)
c) run post-disconnect constraints and actions and on its neighbors
2. if specified node is not a connector (neighbors are connectors),
a) recursively run __delete on each of its neighbors
b) delete it
__deleteConnector:
1. delete all appropriate edges then delete node
delete:
0. create a step-checkpoint
1. wrap __delete in crudOp
2. return err or nothing */
'__delete' :
function(args/*id*/)
{
var id = args.id,
metamodel = this.__getMetamodel(this.model.nodes[id]['$type']),
type = this.__getType(this.model.nodes[id]['$type']),
isConnector = (this.metamodels[metamodel]['connectorTypes'][type] != undefined),
neighbors = [];
this.model.edges.forEach(
function(edge)
{
if( edge['src'] == id && ! _utils.contains(neighbors,edge['dest']) )
neighbors.push(edge['dest']);
else if( edge['dest'] == id && ! _utils.contains(neighbors,edge['src']) )
neighbors.push(edge['src']);
});
if( isConnector )
{
if( (res = this.__crudOp(
metamodel,
['disconnect'],
neighbors,
'__deleteConnector',
{'id':id})) )
return res;
}
else
{
for( var i in neighbors )
if( (res = this.__crudOp(
metamodel,
['delete'],
[neighbors[i]],
'__delete',
{'id':neighbors[i]})) )
return res;
this.__rmnode__(id);
}
},
'__deleteConnector' :
function(args/*id*/)
{
for( var i=0; i<this.model.edges.length; i++ )
{
var edge = this.model.edges[i];
if( edge['src'] == args.id || edge['dest'] == args.id )
this.__rmedge__(i--);
}
this.__rmnode__(args.id);
},
'delete' :
function(id)
{
this.__setStepCheckpoint();
if( this.model.nodes[id] == undefined )
return {'$err':'invalid id :: '+id};
var err = this.__crudOp(
this.__getMetamodel(this.model.nodes[id]['$type']),
['delete'],
[id],
'__delete',
{'id':id});
return err ||
{'changelog':this.__changelog()};
},
/* returns the stringified full model, a stringified node, or a copy of an
attribute's value */
'read' :
function(id,attr)
{
if( id == undefined )
return _utils.jsons(this.model);
else if( this.model.nodes[id] == undefined )
return {'$err':'instance not found :: '+id};
else if( attr == undefined )
return _utils.jsons(this.model.nodes[id]);
else if( attr.match(/.+\/.+/) )
{
var curr = this.model.nodes[id];
for( var i in (path = attr.split('/')) )
if( typeof curr == 'object' && path[i] in curr )
curr = curr[path[i]];
else
return {'$err':'instance '+id+' has no attribute :: '+attr};
}
else if( !(attr in this.model.nodes[id]) )
return {'$err':'instance '+id+' has no attribute :: '+attr};
var attrVal = (curr ? curr['value'] : this.model.nodes[id][attr]['value']);
if( typeof attrVal == 'object' )
return _utils.clone(attrVal);
else
return attrVal;
},
/* returns a copy of one or all metamodels in this.metamodels */
'readMetamodels' :
function(metamodel)
{
if( metamodel == undefined )
return _utils.jsons(this.metamodels);
else if( this.metamodels[metamodel] == undefined )
return {'$err':'metamodel not found :: '+metamodel};
else
return _utils.jsons(this.metamodels[metamodel]);
},
/* returns this.name */
'readName' :
function()
{
return this.name;
},
/* runs accesor-code that conforms to the DesignerCode API and returns its
results */
'runDesignerAccessorCode' :
function(code,desc,id)
{
var res = this.__runDesignerCode(code,desc,'accessor',id);
if( res && res['$err'] )
return res;
return res;
},
/* runs action-code that conforms to the DesignerCode API (of interest is
that this 'operation' is checkpointed and can thus be undone/redone; and
that any exceptions thrown by the code cause a full rollback to before it
was run and are then returned to the querier) */
'runDesignerActionCode' :
function(code,desc,type,id)
{
this.__setStepCheckpoint();
this.__checkpoint();
if( (err = this.__runDesignerCode(code,desc,type,id)) )
{
this.__restoreCheckpoint();
return err;
}
this.__clearCheckpoint();
return {'changelog':this.__changelog()};
},
/* updates node with specified id
__update:
1. update instance as per data
2. return err on unknown attributes
3. TBA: type verification on new values
update:
0. create a step-checkpoint
1. wrap __update in crudOp
2. return err or nothing */
'__update' :
function(args/*id,data*/)
{
for( var attr in args.data )
if( args.data[attr] == null )
return {'$err':'tried to set attribute '+attr+' to "null"'};
else if( (res = this.read(args.id,attr))['$err'] )
return res;
else
this.__chattr__(args.id,attr,args.data[attr]);
},
'update' :
function(id,data/*{..., attr_i:val_i, ...}*/)
{
this.__setStepCheckpoint();
if( this.model.nodes[id] == undefined )
return {'$err':'invalid id :: '+id};
var err = this.__crudOp(
this.__getMetamodel(this.model.nodes[id]['$type']),
['edit'],
[id],
'__update',
{'id':id,
'data':data});
return err ||
{'changelog':this.__changelog()};
},
/*************************** EVENT HANDLER EXEC ****************************/
/* run the given constraint|action|accessor... when id is specified, we
consider it to be the id of the node that "owns" the current
constraint|action|accessor...
this function is divided in 3 parts
1. constraints/actions/accessors API definition
2. safe_eval definition
3. actual code that runs the handler and handles its output */
'__runDesignerCode' :
function(code,desc,type,id)
{
/* the functions below implement the API available for constraints,
actions and 'accessors'... they can only be called from "designer"
code (i.e., from actions/constraints/accessors written by language
and/or model transformation designers)... the main consequence of
this is our design decision that setAttr() is not treated like a
normal crud operation: it does not go through the crudOp pipeline
of pre/post edit constraints/actions... on one hand, this decision
avoids any weird recursion cases (e.g., setAttr() in pre-edit action
triggers pre-edit action and on and on and on)... on the other hand,
designers should be aware that:
1. setAttr() may set attributes to values that the user could not
input (e.g., due to constraints)
2. consequences (specified as edit actions) of a user setting an
attribute A to value 'a' might not take effect if setAttr()
sets attribute A to value 'a' : for instance, if an edit
action says that attribute B should be 'a'+2, setAttr() won't
trigger that action
3. even though setAttr() bypasses crudOp constraints/actions, its
effects are still immediate: a getAttr() on the next line (of
designer code) reports the updated value
moral of story:
designers must be very careful with setAttr() to avoid putting
the model into otherwise unreachable states
API:
hasAttr(_attr[,_id])
return true if the specified node has an attribute of the
given name
getAttr(_attr[,_id])
return the requested attr of the specified node... to ensure
getAttr can't be used to edit the model, JSON parse+stringify
is used to return a *copy* of the attribute when its value has
an object type (i.e., hash or array)
getAllNodes([_fulltypes])
if _fulltypes is undefined, return the ids all of nodes...
otherwise, return ids of all nodes with specified fulltypes
getNeighbors(_dir[,_type,_id])
return all inbound (_dir = '<'), outbound (_dir = '>') or both
(_dir = '*') neighbor ids for specified type (if any)
print(str)
print something to the console that launched the server
setAttr(_attr,_val[,_id])
((this function is only available in actions))... update the
requested attr of the specified node using __chattr__ (s.t.
the change is logged)...
TBA:: type-checking on _val
basic checks are made on input parameters to aid in debugging faulty
actions and constraints... for functions with id parameters, if no
id is given, we use the id passed to __runDesignerCode... which is
either the id of the node that "owns" the current constraint|action|
accessor, or undefined if the parameter was omitted */
var self = this;
function getAttr(_attr,_id)
{
if( _id == undefined )
_id = id;
if( self.model.nodes[_id] == undefined )
throw 'invalid getAttr() id :: '+_id;
else if( !(_attr in self.model.nodes[_id]) )
throw 'invalid getAttr() attribute :: '+_attr;
if( _attr.charAt(0) == '$' )
return self.model.nodes[_id][_attr];
else if( typeof self.model.nodes[_id][_attr]['value'] == 'object' )
return _utils.clone(self.model.nodes[_id][_attr]['value']);
else
return self.model.nodes[_id][_attr]['value'];
}
function getAttrNames(_id)
{
if( _id == undefined )
_id = id;
if( self.model.nodes[_id] == undefined )
throw 'invalid getAttrNames() id :: '+_id;
return Object.getOwnPropertyNames(self.model.nodes[_id]);
}
function hasAttr(_attr,_id)
{
if( _id == undefined )
_id = id;
if( self.model.nodes[_id] == undefined )
throw 'invalid getAttr() id :: '+_id;
return _attr in self.model.nodes[_id];
}
function getAllNodes(_fulltypes)
{
if( _fulltypes != undefined && !(_fulltypes instanceof Array) )
throw 'invalid getAllNodes() types array :: '+_fulltypes;
var ids = [];
for( var _id in self.model.nodes )
{
if( _fulltypes == undefined ||
_utils.contains(_fulltypes,self.model.nodes[_id]['$type']) )
ids.push(_id);
}
return ids;
}
function getNeighbors(_dir,_type,_id)
{
if( _id == undefined )
_id = id;
if( _type == undefined )
_type = '*';
if( self.model.nodes[_id] == undefined )
throw 'invalid getNeighbors() id :: '+_id;
var ids = [];
for( var i in self.model.edges )
{
var edge = self.model.edges[i];
if( edge['src'] == _id &&
(_dir == '>' || _dir == '*' || _dir == "out") &&
(_type == '*' || self.model.nodes[edge['dest']]['$type'] == _type) &&
! _utils.contains(ids,edge['dest']) )
ids.push(edge['dest']);
else if( edge['dest'] == _id &&
(_dir == '<' || _dir == '*' || _dir == "in") &&
(_type == '*' || self.model.nodes[edge['src']]['$type'] == _type) &&
! _utils.contains(ids,edge['src']) )
ids.push(edge['src']);
}
return ids;
}
function print(str)
{
_util.log(str);
}
function setAttr(_attr,_val,_id)
{
if( type != 'action' )
throw 'setAttr() can only be used within actions';
if( _id == undefined )
_id = id;
if( self.model.nodes[_id] == undefined )
throw 'invalid setAttr() id :: '+_id;
else if( !(_attr in self.model.nodes[_id]) || _attr.charAt(0) == '$' )
throw 'invalid setAttr() attribute :: '+_attr;
self.__chattr__(_id,_attr,_val);
}
/* evaluate provided code without the said code having access to
globals (i.e., model, journal) or to 'self' (which we use above to
allow non-global functions to access globals), and catching any
exceptions it may throw... escaped newlines if any are unescaped */
function safe_eval(code)
{
var self = undefined;
try
{
return eval(code);
}
catch(err)
{
if( err == 'IgnoredConstraint' )
return true;
return {'$err':err};
}
}
var res = safe_eval(code);
if( res != undefined && res['$err'] != undefined )
return {'$err':type+' ('+desc+') crashed on :: '+res['$err']};
/* completed accessor */
else if( type == 'accessor' )
return res;
/* failed constraint */
else if( res == false )
return {'$err':type+' ('+desc+') failed'};
},
/* run actions or constraints for specified events and specified nodes
1. get types of specified nodes (note that we do a little hack for the
special case of pre-create handlers because this.model.nodes does not
yet contain a node with the to-be-created node's id... thus its type
is read from this.next_type)
2. identify and run applicable handlers based on events and targetTypes */
'__runEventHandlers' :
function(allHandlers,events,ids,handlerType)
{
var types2ids = {};
for( var i in ids )
{
var id = ids[i];
if( id == this.next_id )
var type = this.__getType(this.next_type);
else if( this.model.nodes[id] == undefined )
continue;
else
var type = this.__getType(this.model.nodes[id]['$type']);
if( types2ids[type] == undefined )
types2ids[type] = [];
types2ids[type].push(id);
}
for (let i in allHandlers) {
let handler = allHandlers[i];
let handled = _utils.contains(events, handler['event']) ||
(_utils.contains(events, "validate") && handler['event'] == ""); //handle legacy events
if (!handled) {
continue;
}
if (handler['targetType'] == '*') {
let result = null;
for (let j in ids) {
result = this.__runDesignerCode(
handler['code'],
handler['event'] + ' ' + handler['name'],
handlerType,
ids[j]);
if (result) {
return result;
}
}
if (ids.length == 0) {
result = this.__runDesignerCode(
handler['code'],
handler['event'] + ' ' + handler['name'],
handlerType);
if (result) {
return result;
}
}
}
else {
for (let j in types2ids[handler['targetType']]) {
let id = types2ids[handler['targetType']][j];
let result = this.__runDesignerCode(
handler['code'],
handler['event'] + ' ' + handler['name'],
handlerType,
id);
if (result) {
return result;
}
}
}
}
},
/**************************** MODEL VALIDATION *****************************/
/* verifies that the current model satisfies (1) the min cardinalities set
by its metamodel(s) and (2) all global eventless constraints... returns
the first encountered discrepancy or nothing
1. count incoming and outgoing connections of each type for each node
2. compare the above to the min cardinalities
3. run all global eventless constraints */
'validateModel' :
function(model)
{
var inCounts = {},
outCounts = {},
model = (model == undefined ? this.model : model),
outContainments = {},
containmentTargets = {};
if( model.nodes == undefined ||
model.edges == undefined ||
model.metamodels == undefined ||
model.metamodels.length == 0 )
return {'$err':'provided model is either empty or not an atompm model'};
for( var i in model.edges )
{
var edge = model.edges[i],
srcType = this.__getType(model.nodes[edge['src']]['$type']),
destType = this.__getType(model.nodes[edge['dest']]['$type']),
srcMetamodel = this.__getMetamodel(model.nodes[edge['src']]['$type']),
destMetamodel = this.__getMetamodel(model.nodes[edge['dest']]['$type']);
if( inCounts[edge['dest']] == undefined )
inCounts[edge['dest']] = {};
if( inCounts[edge['dest']][srcType] == undefined )
inCounts[edge['dest']][srcType] = 0;
inCounts[edge['dest']][srcType]++;
if( outCounts[edge['src']] == undefined )
outCounts[edge['src']] = {};
if( outCounts[edge['src']][destType] == undefined )
outCounts[edge['src']][destType] = 0;
outCounts[edge['src']][destType]++;
if ( outContainments[edge['src']] == undefined ) {
outContainments[edge['src']] = [];
}
if (destType in this.metamodels[destMetamodel]['connectorTypes'] && this.metamodels[destMetamodel]['connectorTypes'][destType] == 'containment') {
outContainments[edge['src']].push(edge['dest']);
}
if ( containmentTargets[edge['src']] == undefined ) {
containmentTargets[edge['src']] = [];
}
if (srcType in this.metamodels[srcMetamodel]['connectorTypes'] && this.metamodels[srcMetamodel]['connectorTypes'][srcType] == 'containment') {
containmentTargets[edge['src']].push(edge['dest']);
}
}
var checked_for_loops = [];
for( var id in model.nodes )
{
var metamodel = this.__getMetamodel(model.nodes[id]['$type']),
type = this.__getType(model.nodes[id]['$type']);
for( var i in this.metamodels[metamodel]['cardinalities'][type] )
{
var cardinality = this.metamodels[metamodel]['cardinalities'][type][i],
tc = cardinality['type'];
if( cardinality['dir'] == 'out' &&
cardinality['min'] > (outCounts[id] == undefined || outCounts[id][tc] == undefined ? 0 : outCounts[id][tc]) )
return {'$err':'insufficient outgoing connections of type '+tc+' for '+model.nodes[id]['$type']+'/'+id};
else if( cardinality['dir'] == 'in' &&
cardinality['min'] > (inCounts[id] == undefined || inCounts[id][tc] == undefined ? 0 : inCounts[id][tc]) )
return {'$err':'insufficient incoming connections of type '+tc+' for '+model.nodes[id]['$type']+'/'+id};
}
if (checked_for_loops.indexOf(id) < 0 && !(type in this.metamodels[metamodel]['connectorTypes'])) {
var visited = [],
tv = [id];
// eslint-disable-next-line no-inner-declarations
function dfs(to_visit) {
var curr = to_visit.pop();
if( curr == undefined )
return undefined; // no more to check
else if( visited.indexOf(curr) > -1 )
return {'$err':'containment loop found for ' + model.nodes[id]['$type']+'/'+id}; // error: loop found!
else {
visited.push(curr);
// find all (containment) associations linked to the object, and add their targets to the to_visit list.
for ( var oc_idx in outContainments[curr] ) {
to_visit = to_visit.concat(containmentTargets[outContainments[curr][oc_idx]]);
}
return dfs( to_visit );
}
}
var res = dfs(tv);
if (res != undefined) {
return res;
}
checked_for_loops= checked_for_loops.concat(visited);
}
}
for (let metamodel in this.metamodels) {
let err = this.__runEventHandlers(this.metamodels[metamodel]['constraints'], ['validate'], [], 'constraint');
if (err)
return err;
}
},
/**************************** MODEL COMPILATION ****************************/
/* compile the current model and the given CS model into an icon definition
metamodel
0. the entire function body is wrapped in a try/catch... this is our lazy
approach to verifying that the current model is indeed a valid model of
an icon definition metamodel
1. if the current model is missing the CS formalism, return error
2. extract information about types from current model
a) find all ConcreteSyntax/Icons and ConcreteSyntax/Links
b) map all CS/Icons to their IconIcon in the CS model (argument)
c) map all CS/Icons to the nodes they're [transitively] connected to
(except their IconContents links)
d) save all edges between contained nodes from step c)
e) enhance every contained node (from step c)) with information about
its associated IconIcon (e.g., position, orientation)... this is
needed so that the final '$contents' attributes of each generated
*Icon hold sufficient information to render icons as the user
specified them... note that position attributes are adjusted to make