فهرست منبع

merge with master

Simon Van Mierlo 9 سال پیش
والد
کامیت
8dab9ff706
100فایلهای تغییر یافته به همراه9374 افزوده شده و 2692 حذف شده
  1. 75 0
      addis/PM_Example.mvc
  2. 164 0
      addis/PM_MetaModel.mvc
  3. 97 0
      addis/PM_example2.mvc
  4. 2111 0
      addis/PM_to_SCCD.mvc
  5. 406 0
      addis/SCCD_Example.mvc
  6. 271 0
      addis/SCCD_MetaModel.mvc
  7. 45 0
      addis/Test_PM2SCCD.py
  8. 18 23
      bootstrap/core_formalism.mvc
  9. 264 0
      bootstrap/99_core.mvc
  10. 1 17
      bootstrap/bootstrap.py
  11. 8 0
      bootstrap/bottom.mvc
  12. 49 0
      bootstrap/compiler.alc
  13. 85 0
      bootstrap/conformance_finding.alc
  14. 31 53
      bootstrap/conformance_scd.alc
  15. 168 116
      bootstrap/constructors.alc
  16. 906 753
      bootstrap/core_algorithm.alc
  17. 4 0
      bootstrap/initial_code_manager.alc
  18. 8 1
      bootstrap/initial_code_task.alc
  19. 36 0
      bootstrap/io.alc
  20. 2 2
      bootstrap/library.alc
  21. 6 0
      bootstrap/manual.mvc
  22. 0 48
      bootstrap/metamodels.alt
  23. 67 14
      bootstrap/mini_modify.alc
  24. 45 71
      bootstrap/model_management.alc
  25. 108 105
      bootstrap/modelling.alc
  26. 24 83
      bootstrap/object_operations.alc
  27. 6 2
      bootstrap/pm.mvc
  28. 1 299
      bootstrap/primitives.alc
  29. 14 23
      bootstrap/ramify.alc
  30. 1 1
      bootstrap/random.alc
  31. 442 0
      bootstrap/semi_primitives.alc
  32. 93 0
      bootstrap/services.alc
  33. 98 91
      bootstrap/transform.alc
  34. 41 0
      bootstrap/typing.alc
  35. 102 0
      bootstrap/utils.alc
  36. 1 1
      doc/Makefile
  37. 184 12
      doc/actionlanguage.rst
  38. 20 0
      doc/bootstrap.rst
  39. 25 0
      doc/concrete_syntax.rst
  40. 5 5
      doc/conf.py
  41. 19 0
      doc/conformance.rst
  42. 15 0
      doc/developer.rst
  43. 12 7
      doc/index.rst
  44. 33 38
      doc/installation.rst
  45. 94 0
      doc/interaction.rst
  46. 3 3
      doc/internal.rst
  47. 18 0
      doc/language_engineer.rst
  48. 103 0
      doc/languageengineer_modellanguage.rst
  49. 184 0
      doc/metamodelling.rst
  50. 0 98
      doc/mini_modify.rst
  51. 4 0
      doc/model.rst
  52. 0 209
      doc/modellanguage.rst
  53. 16 0
      doc/modeller.rst
  54. 186 0
      doc/modeller_modellanguage.rst
  55. 189 0
      doc/modelling.rst
  56. 0 211
      doc/mvc.rst
  57. 24 0
      doc/operations.rst
  58. 138 0
      doc/permissions.rst
  59. 26 0
      doc/primitives.rst
  60. 14 0
      doc/problems.rst
  61. 46 0
      doc/process_enactment.rst
  62. 0 0
      doc/scripts.rst
  63. 19 0
      doc/services.rst
  64. 75 0
      doc/transformations.rst
  65. 31 0
      doc/users.rst
  66. 1225 0
      doc/wrappers.rst
  67. 6 4
      hybrid_server/classes/mvkcontroller.xml
  68. 123 0
      hybrid_server/classes/service.xml
  69. 117 78
      hybrid_server/classes/task.xml
  70. 2 0
      hybrid_server/server.xml
  71. 176 0
      integration/code/minimal_SCCD.mvc
  72. 12 3
      integration/code/pm_pn_reachability.mvc
  73. 1 7
      integration/code/pn_simulate.alc
  74. 2 2
      integration/code/reachabilitygraph_print.mvc
  75. 12 0
      integration/code/simple_client.alc
  76. 118 88
      integration/test_mvc.py
  77. 131 58
      integration/test_powerwindow.py
  78. 3 38
      integration/utils.py
  79. 3 5
      interface/HUTN/grammars/actionlanguage.g
  80. 1 28
      interface/HUTN/hutn_compiler/bootstrap_visitor.py
  81. 48 21
      interface/HUTN/hutn_compiler/compiler.py
  82. 22 23
      interface/HUTN/hutn_compiler/constructors_visitor.py
  83. 2 2
      interface/HUTN/hutn_compiler/model_bootstrap_visitor.py
  84. 1 1
      interface/HUTN/hutn_compiler/model_visitor.py
  85. 29 38
      interface/HUTN/hutn_compiler/primitives_visitor.py
  86. 4 2
      interface/HUTN/hutn_compiler/semantics_visitor.py
  87. 2 0
      interface/HUTN/includes/compiler.alh
  88. 1 0
      interface/HUTN/includes/conformance_finding.alh
  89. 1 0
      interface/HUTN/includes/conformance_scd.alh
  90. 1 0
      interface/HUTN/includes/constructors.alh
  91. 10 0
      interface/HUTN/includes/core_algorithm.alh
  92. 2 1
      interface/HUTN/includes/io.alh
  93. 0 1
      interface/HUTN/includes/model_management.alh
  94. 2 0
      interface/HUTN/includes/modelling.alh
  95. 0 3
      interface/HUTN/includes/object_operations.alh
  96. 16 3
      interface/HUTN/includes/primitives.alh
  97. 7 0
      interface/HUTN/includes/services.alh
  98. 6 0
      interface/HUTN/includes/typing.alh
  99. 7 0
      interface/HUTN/includes/utils.alh
  100. 0 0
      interface/HUTN/test/constructor_compilation_action_language/expected/action

+ 75 - 0
addis/PM_Example.mvc

@@ -0,0 +1,75 @@
+Start start {
+    id = "start"
+    {Next} Exec A {
+        name = "A"
+        id = "A"
+        {Next} Fork fork_1 {
+            {Next} Exec B {
+                name = "A"
+                id = "A"
+            }
+            {Next} Exec C {
+                name = "C"
+                id = "C"
+            }
+            {Next} Exec E {
+                name = "E"
+                id = "E"
+                {Produces} Data data {
+                    id = "data"
+                    name = "True"
+                    type = "Boolean"
+                }
+            }
+        }
+    }
+}
+Join join_1 {
+    id = "join_1"
+}
+Join join_2 {
+    id = "join_2"
+}
+Next (B,join_1){
+    id = "B_join_1"
+}
+Next (C,join_1){
+    id = "C_join_1"
+}
+Exec D {
+    name = "D"
+    id = "D"
+}
+Next (join_1, D){
+    id = "join_1_D"
+}
+Next (D, join_2){
+    id = "D_join_2"
+}
+Next (E, join_2){
+    id = "E_join_2"
+}
+Exec F {
+    name = "F"
+    id = "F"
+}
+Decision decision_1 {
+    id = "decision_1"
+}
+DecisionConsumes (decision_1, data) {
+    id = "decision_1_data"
+}
+Next (F, decision_1){
+    id = "F_decision_1"
+}
+Next (decision_1, A){
+    id = "decision_1_A"
+    value = "True"
+}
+Finish end {
+    id = "finish"
+}
+Next (decision_1, end){
+    id = "decision_1_end"
+    value = "False"
+}

+ 164 - 0
addis/PM_MetaModel.mvc

@@ -0,0 +1,164 @@
+include "primitives.alh"
+include "object_operations.alh"
+include "modelling.alh"
+
+SimpleAttribute String {}
+SimpleAttribute MvCName {
+    constraint = $
+        String function constraint(model : Element, name : String):
+            if (bool_not(is_physical_string(model["model"][name]))):
+                return "MvCName has no string value"!
+            else:
+                return "OK"!
+        $
+}
+SimpleAttribute Natural {
+    constraint =$
+    String function constraint(model: Element, id: String):
+        if (bool_not(is_physical_int(model["model"][id]))):
+            return "Natural has no integer value at " + id!
+        elif (integer_lt(model["model"][id], 0)):
+            return "Natural does not have a positive or zero value at " + id!
+        else:
+            return "OK"!
+     $
+}
+Class Model {
+    items_creation_order ?: String
+    SCCD_id : String
+}
+Class Activity {
+    id : String
+}
+Class Edge {
+    id : String
+}
+Class Start : Activity {
+    lower_cardinality = 1
+    upper_cardinality = 1
+}
+Class Finish : Activity {
+    lower_cardinality = 1
+    constraint = $
+        String function constraint(model : Element, name : String):
+            Element incoming_edges
+            incoming_edges = allIncomingAssociationInstances(model, name, "Next")
+            if list_len(incoming_edges) !=1:
+                return "A finish node should have exactly one incoming control-flow at " + name!
+            else:
+                return "OK"!
+        $
+}
+Class Fork : Activity {
+    constraint = $
+        String function constraint(model : Element, name : String):
+            Element incoming_edges
+            incoming_edges = allIncomingAssociationInstances(model, name, "Next")
+            if list_len(incoming_edges) <1:
+                return "A Fork node should have at-least one incoming control-flow at " + name!
+            else:
+                return "OK"!
+        $
+}
+Class Join : Activity {
+    constraint = $
+        String function constraint(model : Element, name : String):
+            Element incoming_edges
+            Element source
+            String type
+            incoming_edges = allIncomingAssociationInstances(model, name, "Next")
+            if list_len(incoming_edges) >0:
+                Integer i
+                i = 0
+                while i < list_len (incoming_edges):
+                    source = readAssociationSource(model, list_read(incoming_edges, i))
+                    type = read_type(model, source)
+                    if type == "Start":
+                        return "A join node can not have a Start node as an incoming flow at "+name!
+            if list_len(incoming_edges) <2:
+                return "A Join node should have at least two incoming control flows at " + name!
+            else:
+                return "OK"!
+        $
+}
+Class Decision : Activity {
+    constraint = $
+        String function constraint(model : Element, name : String):
+            Element incoming_edges
+            incoming_edges = allIncomingAssociationInstances(model, name, "Next")
+            if list_len(incoming_edges) <1:
+                return "A Decision node should have at least one incoming control-flows at " + name!
+            else:
+                return "OK"!
+        $
+}
+Class Exec : Activity {
+    name : MvCName
+    sccd_class_id ?: String
+    lower_cardinality = 1
+    constraint = $
+        String function constraint(model : Element, name : String):
+            Element incoming_edges
+            incoming_edges = allIncomingAssociationInstances(model, name, "Next")
+            if list_len(incoming_edges) <1:
+                return "An Executable node should have at-least one incoming control-flow at " + name!
+            else:
+                return "OK"!
+        $
+}
+Class Data {
+    id : String
+    name : MvCName
+    type : MvCName
+}
+
+Association Produces : Edge (Exec, Data) {
+    source_lower_cardinality = 1
+}
+Association Consumes : Edge (Exec, Data) {}
+Association DecisionConsumes : Edge (Decision, Data) {
+    target_lower_cardinality = 1
+    target_upper_cardinality = 1
+}
+Association Next : Edge (Activity, Activity) {
+    value ?: MvCName
+}
+Association S2A : Next(Start, Activity){
+    target_lower_cardinality = 1
+    target_upper_cardinality = 1
+}
+Association E2A : Next(Exec, Activity){
+    target_lower_cardinality = 1
+    target_upper_cardinality = 1
+}
+Association F2A : Next(Fork, Activity){
+    target_lower_cardinality = 2
+}
+Association J2A : Next(Join, Activity){
+    target_lower_cardinality = 1
+    target_upper_cardinality = 1
+}
+Association D2A : Next(Decision, Activity){
+    target_lower_cardinality = 2
+}
+
+Class CanvasPosition{
+    x1: Natural
+    y1: Natural
+    x2 ?: Natural
+    y2 ?: Natural
+}
+Association activity_position (Activity, CanvasPosition){}
+Association data_position (Data, CanvasPosition){}
+Association produces_positions (Produces, CanvasPosition){
+    order: Natural
+}
+Association consumes_positions (Consumes, CanvasPosition){
+    order: Natural
+}
+Association decision_consumes_positions (DecisionConsumes, CanvasPosition){
+    order: Natural
+}
+Association next_positions (Next, CanvasPosition){
+    order: Natural
+}

+ 97 - 0
addis/PM_example2.mvc

@@ -0,0 +1,97 @@
+Start start {
+    id = "start"
+}
+Exec A {
+    name = "A"
+    id = "A"
+}
+S2A (start, A){
+    id ="start_A"
+}
+Fork fork_1 {
+    id = "fork_1"
+}
+E2A (A, fork_1){
+    id = "A_fork_1"
+}
+Exec B {
+    name = "B"
+    id = "B"
+}
+Exec C {
+    name = "C"
+    id = "C"
+}
+Exec E {
+    name = "E"
+    id = "E"
+}
+F2A (fork_1, B){
+    id = "fork_1_B"
+}
+F2A (fork_1, C){
+    id = "fork_1_C"
+}
+F2A (fork_1, E){
+    id = "fork_1_E"
+}
+Data data {
+    id = "data"
+    name = "bool"
+    type = "Boolean"
+}
+Produces (E, data){
+    id = "E_data"
+}
+Join join_1 {
+    id = "join_1"
+}
+Join join_2 {
+    id = "join_2"
+}
+E2A (B,join_1){
+    id = "B_join_1"
+}
+E2A (C,join_1){
+    id = "C_join_1"
+}
+Exec D {
+    name = "D"
+    id = "D"
+}
+J2A (join_1, D){
+    id = "join_1_D"
+}
+E2A (D, join_2){
+    id = "D_join_2"
+}
+E2A (E, join_2){
+    id = "E_join_2"
+}
+Exec F {
+    name = "F"
+    id = "F"
+}
+J2A (join_2, F){
+    id = "join_2_f"
+}
+Decision decision_1 {
+    id = "decision_1"
+}
+DecisionConsumes (decision_1, data) {
+    id = "decision_1_data"
+}
+E2A (F, decision_1){
+    id = "F_decision_1"
+}
+D2A (decision_1, A){
+    id = "decision_1_A"
+    value = "True"
+}
+Finish end {
+    id = "finish"
+}
+D2A (decision_1, end){
+    id = "decision_1_end"
+    value = "False"
+}

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 2111 - 0
addis/PM_to_SCCD.mvc


+ 406 - 0
addis/SCCD_Example.mvc

@@ -0,0 +1,406 @@
+include "primitives.alh"
+Diagram SCCD_my_PM {
+    name = "SCCD example "
+    {diagram_classes} Class A {
+        name = "A"
+        constructor_body = $
+            Void function constructor(attributes : Element, parameters : Element):
+                dict_add(attributes, "id", '')
+                dict_add(attributes, "parent_id", '')
+                return !
+        $
+        {behaviour} CompositeState root_a {
+            name = "main"
+            isInitial = True
+            {composite_children} BasicState initial_a {
+                name = "Init"
+                isInitial = True
+            }
+            {composite_children} BasicState running_a {
+                name = "Running"
+                isInitial = False
+            }
+            {composite_children} BasicState done_a {
+                name = "Done"
+                isInitial = False
+            }
+        }
+    }
+    {diagram_classes} Class B {
+        name = "B"
+        constructor_body = $
+            Void function constructor(attributes : Element, parameters : Element):
+                dict_add(attributes, "id", '')
+                dict_add(attributes, "parent_id", '')
+                return !
+        $
+        {behaviour} CompositeState root_b {
+            name = "main"
+            isInitial = True
+            {composite_children} BasicState initial_b {
+                name = "Init"
+                isInitial = True
+            }
+            {composite_children} BasicState running_b {
+                name = "Running"
+                isInitial = False
+            }
+            {composite_children} BasicState done_b {
+                name = "Done"
+                isInitial = False
+            }
+        }
+    }
+    {diagram_classes} Class C {
+        name = "C"
+        constructor_body = $
+            Void function constructor(attributes : Element, parameters : Element):
+                dict_add(attributes, "id", '')
+                dict_add(attributes, "parent_id", '')
+                return !
+        $
+        {behaviour} CompositeState root_c {
+            name = "main"
+            isInitial = True
+            {composite_children} BasicState initial_c {
+                name = "Init"
+                isInitial = True
+            }
+            {composite_children} BasicState running_c {
+                name = "Running"
+                isInitial = False
+            }
+            {composite_children} BasicState done_c {
+                name = "Done"
+                isInitial = False
+            }
+        }
+    }
+    {diagram_classes} Class E {
+        name = "E"
+        constructor_body = $
+            Void function constructor(attributes : Element, parameters : Element):
+                dict_add(attributes, "id", '')
+                dict_add(attributes, "parent_id", '')
+                return !
+        $
+        {behaviour} CompositeState root_e {
+            name = "main"
+            isInitial = True
+            {composite_children} BasicState initial_e {
+                name = "Init"
+                isInitial = True
+            }
+            {composite_children} BasicState running_e {
+                name = "Running"
+                isInitial = False
+                {onEntryRaise} Raise {
+                    event = "save"
+                    scope = "narrow"
+                    target = $
+                        Element function raise(attributes : Element):
+                            return attributes["parent_id"]!
+                        $
+                    parameter = $
+                        Element function raise(attributes : Element):
+                            Element result
+                            result = list_create()
+                            list_append(result, "bool")
+                            list_append(result, "E")
+                            return result!
+                    $
+                }
+            }
+            {composite_children} BasicState done_e {
+                name = "Done"
+                isInitial = False
+            }
+        }
+    }
+    {diagram_classes} Class D {
+        name = "D"
+        constructor_body = $
+            Void function constructor(attributes : Element, parameters : Element):
+                dict_add(attributes, "id", '')
+                dict_add(attributes, "parent_id", '')
+                return !
+        $
+        {behaviour} CompositeState root_d {
+            name = "main"
+            isInitial = True
+            {composite_children} BasicState initial_d {
+                name = "Init"
+                isInitial = True
+            }
+            {composite_children} BasicState running_d {
+                name = "Running"
+                isInitial = False
+            }
+            {composite_children} BasicState done_d {
+                name = "Done"
+                isInitial = False
+            }
+        }
+    }
+    {diagram_classes} Class F {
+        name = "F"
+        constructor_body = $
+            Void function constructor(attributes : Element, parameters : Element):
+                dict_add(attributes, "id", '')
+                dict_add(attributes, "parent_id", '')
+                return !
+        $
+        {behaviour} CompositeState root_f {
+            name = "main"
+            isInitial = True
+            {composite_children} BasicState initial_f {
+                name = "Init"
+                isInitial = True
+            }
+            {composite_children} BasicState running_f {
+                name = "Running"
+                isInitial = False
+            }
+            {composite_children} BasicState done_f {
+                name = "Done"
+                isInitial = False
+            }
+        }
+    }
+
+}
+transition (initial_a, running_a){
+    event = "set_id"
+    script = $
+            Void function script(attributes : Element, parameters : Element):
+                dict_overwrite(attributes, "id", parameters[0])
+                dict_overwrite(attributes, "parent_id", parameters[1])
+                log("CREATED ---- A")
+                return!
+        $
+}
+transition (running_a, done_a){
+    after = $
+            Float function after(attributes : Element):
+                return 0.5!
+        $
+    script = $
+            Void function script(attributes : Element, parameters : Element):
+                log("FINISHED ---- A")
+                return!
+        $
+    {transition_raises} Raise {
+        scope = "narrow"
+        event = "terminated"
+        target = $
+            String function raise(attributes : Element):
+                return attributes["parent_id"]!
+            $
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, 'A')
+                return result!
+        $
+    }
+    {transition_raises} Raise {
+        scope = "cd"
+        event = "delete_instance"
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, attributes["id"])
+                return result!
+        $
+    }
+}
+transition (initial_b, running_b){
+    event = "set_id"
+    script = $
+        Void function script(attributes : Element, parameters : Element):
+            dict_overwrite(attributes, "id", parameters[0])
+            dict_overwrite(attributes, "parent_id", parameters[1])
+            log("CREATED ---- B")
+            return!
+    $
+}
+transition (running_b, done_b){
+    after = $
+        Float function after(attributes : Element):
+            return 0.9!
+    $
+    script = $
+        Void function script(attributes : Element, parameters : Element):
+            log("FINISHED ---- B")
+            return!
+    $
+    {transition_raises} Raise {
+        scope = "narrow"
+        event = "terminated"
+        target = $
+            Element function raise(attributes : Element):
+                return attributes["parent_id"]!
+            $
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, 'B')
+                return result!
+        $
+    }
+    {transition_raises} Raise {
+        scope = "cd"
+        event = "delete_instance"
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, attributes["id"])
+                return result!
+        $
+    }
+}
+transition (initial_c, running_c){
+    event = "set_id"
+    script = $
+        Void function script(attributes : Element, parameters : Element):
+            dict_overwrite(attributes, "id", parameters[0])
+            dict_overwrite(attributes, "parent_id", parameters[1])
+            log("CREATED ---- C")
+            return!
+    $
+}
+transition (running_c, done_c){
+    after = $
+        Float function after(attributes : Element):
+            return 0.5!
+    $
+    script = $
+        Void function script(attributes : Element, parameters : Element):
+            log("FINISHED ---- C")
+            return!
+    $
+    {transition_raises} Raise {
+        scope = "narrow"
+        event = "terminated"
+        target = $
+            Element function raise(attributes : Element):
+                return attributes["parent_id"]!
+            $
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, "C")
+                return result!
+        $
+    }
+    {transition_raises} Raise {
+        scope = "cd"
+        event = "delete_instance"
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, attributes["id"])
+                return result!
+        $
+    }
+}
+transition (initial_e, running_e){
+    event = "set_id"
+    script = $
+        Void function script(attributes : Element, parameters : Element):
+            dict_overwrite(attributes, "id", parameters[0])
+            dict_overwrite(attributes, "parent_id", parameters[1])
+            log("CREATED ---- E")
+            return!
+    $
+}
+transition (running_e, done_e){
+    after = $
+        Float function after(attributes : Element):
+            return 0.5!
+    $
+    script = $
+        Void function script(attributes : Element, parameters : Element):
+            log("FINISHED ---- E")
+            return!
+    $
+    {transition_raises} Raise {
+        scope = "narrow"
+        event = "terminated"
+        target = $
+            Element function raise(attributes : Element):
+                return attributes["parent_id"]!
+            $
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, "E")
+                return result!
+        $
+    }
+    {transition_raises} Raise {
+        scope = "cd"
+        event = "delete_instance"
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, attributes["id"])
+                return result!
+        $
+    }
+}
+transition (initial_f, running_f){
+    event = "set_id"
+    script = $
+        Void function script(attributes : Element, parameters : Element):
+            dict_overwrite(attributes, "id", parameters[0])
+            dict_overwrite(attributes, "parent_id", parameters[1])
+            log("CREATED ---- F")
+            return!
+    $
+}
+transition (running_f, done_f){
+    after = $
+            Float function after(attributes : Element):
+                return 0.5!
+        $
+    script = $
+            Void function script(attributes : Element, parameters : Element):
+                log("FINISHED ---- F")
+                return!
+        $
+    {transition_raises} Raise {
+        scope = "narrow"
+        event = "terminated"
+        target = $
+            Element function raise(attributes : Element):
+                return attributes["parent_id"]!
+            $
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, attributes['id'])
+                return result!
+        $
+    }
+    {transition_raises} Raise {
+        scope = "cd"
+        event = "delete_instance"
+        parameter = $
+            Element function raise(attributes : Element, parameters : Element):
+                Element result
+                result = list_create()
+                list_append(result, attributes["id"])
+                return result!
+        $
+    }
+}

+ 271 - 0
addis/SCCD_MetaModel.mvc

@@ -0,0 +1,271 @@
+include "primitives.alh"
+include "object_operations.alh"
+include "modelling.alh"
+
+SimpleAttribute Action {}
+SimpleAttribute Neutral {}
+SimpleAttribute Boolean {
+    constraint = $
+    String function constraint(model: Element, id: String):
+        if (bool_not(is_physical_boolean(model["model"][id]))):
+            return "Boolean has no boolean value at " + id!
+        else:
+            return "OK"!
+    $
+}
+SimpleAttribute String {
+    constraint = $
+    String function constraint(model: Element, id: String):
+        if (bool_not(is_physical_string(model["model"][id]))):
+            return "String has no string value at " + id!
+        else:
+            return "OK"!
+    $
+}
+SimpleAttribute Natural {
+    constraint =$
+    String function constraint(model: Element, id: String):
+        if (bool_not(is_physical_int(model["model"][id]))):
+            return "Natural has no integer value at " + id!
+        elif (integer_lt(model["model"][id], 0)):
+            return "Natural does not have a positive or zero value at " + id!
+        else:
+            return "OK"!
+     $
+}
+SimpleAttribute PositiveFloat {
+    constraint =$
+    String function constraint(model: Element, id: String):
+        if (bool_not(is_physical_float(model["model"][id]))):
+            return "PositiveFloat has no float value at " + id!
+        elif (integer_lt(model["model"][id], 0)):
+            return "PositiveFloat does not have a positive or zero value at " + id!
+        else:
+            return "OK"!
+     $
+}
+SimpleAttribute EventScope {
+    constraint =$
+    String function constraint(model: Element, id: String):
+        String self
+        self = model["model"][id]
+        if (bool_not(is_physical_string(self))):
+            return "EventScope has no string value at " + id!
+        elif (bool_and(bool_and(bool_and(self != "broad", self != "cd"), bool_and(self != "narrow", self != "output")), self != "local")):
+            return "EventScope can be either 'local', 'broad', 'cd', 'narrow' or 'output' and it does not have a proper value at " + id!
+        else:
+            return "OK"!
+    $
+}
+
+Class Diagram{
+    name : String
+    author ?: String
+    description ?: String
+    top ?: String
+    class_reference_items ?: String
+    lower_cardinality = 1
+    upper_cardinality = 1
+}
+Class Inport{
+    name: String
+}
+Class Outport{
+    name: String
+}
+Association diagram_inports(Diagram, Inport){}
+Association diagram_outports(Diagram, Outport){}
+
+Class Class{
+    name : String
+    constructor_body ?: Action
+    destructor ?: Action
+    default ?: Boolean
+    external ?: Boolean
+    class_behaviour_items ?: String
+}
+Association diagram_classes(Diagram, Class){
+    target_lower_cardinality = 1
+}
+
+Class Attribute{
+    name : String
+    type ?: String
+}
+Association class_attributes(Class, Attribute){}
+
+Class Method{
+    name : String
+    body : Action
+    return_type ?: String
+}
+
+Class FormalParameter{
+    name: String
+    type ?: String
+    default ?: String
+}
+Association method_parameters(Method, FormalParameter){}
+Association class_methods(Class, Method){}
+Association class_constructor_parameters(Class, FormalParameter){}
+
+Class CanvasPosition{
+    x1: Natural
+    y1: Natural
+    x2 ?: Natural
+    y2 ?: Natural
+}
+Association class_ref_position(Class, CanvasPosition){
+    target_upper_cardinality = 1
+}
+Association class_beh_position(Class, CanvasPosition){
+    target_upper_cardinality = 1
+}
+
+Association association(Class, Class){
+    name : String
+    min ?: Natural
+    max ?: Natural
+    source_upper_cardinality = 1
+}
+Association association_positions(association, CanvasPosition){
+    order: Natural
+}
+
+Association inheritance(Class, Class){
+    priority ?: Natural
+    source_upper_cardinality = 1
+}
+
+Class SuperClassConstructorParameter{
+    value : Neutral
+}
+Association inheritance_parent_constructor_parameters(inheritance, SuperClassConstructorParameter){
+    order : Natural
+}
+Association inheritance_positions(inheritance, CanvasPosition){
+    order: Natural
+}
+
+Class State{
+    name : String
+    state_reference_path ?: String
+}
+Association state_position(State, CanvasPosition){
+    target_upper_cardinality = 1
+}
+
+Class BasicState : State{
+    isInitial ?: Boolean
+    onEntryScript ?: Action
+    onExitScript ?: Action
+}
+
+Class ActualParameter{
+    exp: String
+}
+
+Class Raise{
+    event: String
+    scope ?: EventScope
+    port ?: String
+    target ?: String
+    parameter ?: Action
+}
+Association raise_parameters(Raise, ActualParameter){
+    order : Natural
+}
+Association onEntryRaise(BasicState, Raise){
+    order : Natural
+}
+Association onExitRaise(BasicState, Raise){
+    order ?: Natural
+}
+
+Class CompositeState : BasicState{}
+Association composite_children(CompositeState, State){
+    source_upper_cardinality = 1
+}
+Association behaviour(Class, CompositeState){
+    target_lower_cardinality = 1
+    target_upper_cardinality = 1
+}
+Association behaviour_positions(behaviour, CanvasPosition){
+    order: Natural
+}
+
+Class ParallelState : BasicState{}
+Association parallel_children(ParallelState, CompositeState){
+    source_upper_cardinality = 1
+}
+
+Class HistoryState : State{
+    type : String
+}
+
+Association transition(State, State){
+    name ?: String
+    cond ?: Action
+    script ?: Action
+    after ?: Action
+    event ?: String
+    port ?: String
+    source_upper_cardinality = 1
+}
+Association transition_parameters(transition, FormalParameter){
+    order : Natural
+}
+Association transition_raises(transition, Raise){
+    order : Natural
+}
+Association transition_positions(transition, CanvasPosition){
+    order: Natural
+}
+
+GlobalConstraint {
+        global_constraint = $
+            String function constraint(model : Element):
+                Element composite_states
+                Element parallel_states
+                Element children
+                String state
+                String child
+                String name
+                Boolean CompInitialFound
+                Element encountered_names
+
+                composite_states = allInstances(model, "CompositeState")
+                parallel_states = allInstances(model, "ParallelState")
+
+                while (list_len(composite_states) >0):
+                    CompInitialFound = False
+                    encountered_names = create_node()
+                    state = set_pop(composite_states)
+                    children = allAssociationDestinations(model, state, "composite_children")
+                    while (list_len(children)>0):
+                        child = set_pop(children)
+                        name = read_attribute(model, child, 'name')
+                        if (set_in(encountered_names, name)):
+                            return "Unique state identifier names on the same level/parent violated"!
+                        else:
+                            set_add(encountered_names, name)
+                        if bool_and(read_type(model, child) != 'HistoryState' , read_attribute(model, child, 'isInitial')):
+                            CompInitialFound = True
+                    if CompInitialFound == False:
+                        return "Composite state does not have an initial child state"!
+
+                while (list_len(parallel_states) >0):
+                    encountered_names = create_node()
+                    state = set_pop(parallel_states)
+                    children = allAssociationDestinations(model, state, "parallel_children")
+                    while (list_len(children)>0):
+                        child = set_pop(children)
+                        name = read_attribute(model, child, 'name')
+                        if (set_in(encountered_names, name)):
+                            return "Unique state identifier names on the same level/parent violated"!
+                        else:
+                            set_add(encountered_names, name)
+
+                return "OK"!
+        $
+    }

+ 45 - 0
addis/Test_PM2SCCD.py

@@ -0,0 +1,45 @@
+import sys
+sys.path.append("wrappers")
+from  modelverse import *
+
+try:
+    init()
+    login('admin', 'admin')
+    model_add('PM', "SimpleClassDiagrams", open("addis/PM_MetaModel.mvc", "r").read())
+except Exception as e:
+    print e
+try:
+    model_add('SCCD', "SimpleClassDiagrams", open("addis/SCCD_MetaModel.mvc", "r").read())
+except Exception as e:
+    print e
+
+if "my_PM" in [i[0] for i in model_list()]:
+    model_delete("my_PM")
+model_add("my_PM", "PM", open("addis/PM_example2.mvc", 'r').read())
+print "PM instance model added"
+#print verify('my_PM')
+if "SCCD_my_PM" in [i[0] for i in model_list()]:
+    model_delete("SCCD_my_PM")
+model_add("SCCD_my_PM", "SCCD", open("addis/SCCD_Example.mvc", 'r').read())
+print "SCCD instance model added"
+print verify('SCCD_my_PM')
+
+def Activity2State():
+    instantiate(None, "Association", ("PM/Activity", "SCCD/CompositeState"), ID="Activity2State_link")
+print "before mt_add"
+print transformation_add_MT({"PM":"PM","SCCD":"SCCD"}, {"SCCD":"SCCD"}, "PM2SCCD", open("addis/PM_to_SCCD.mvc", "r").read(), Activity2State)
+print "mt_add_finished"
+print transformation_execute_MT("PM2SCCD", {"PM":"my_PM", "SCCD":"SCCD_my_PM"}, {"SCCD":"PM_2_SCCD_output"})
+
+alter_context("PM_2_SCCD_output", "SCCD")
+model =  element_list_nice("PM_2_SCCD_output")
+for m in model:
+    print m
+
+
+print("Upload SCCD execution semantics")
+# Add SCCD execution semantics
+transformation_add_AL({"SCCD": "SCCD"}, {}, "SCCD_execute", open("models/SCCD_execute.alc", 'r').read())
+print("DONE")
+transformation_execute_AL("SCCD_execute", {"SCCD": "PM_2_SCCD_output"}, {})
+print("Executed")

+ 18 - 23
bootstrap/core_formalism.mvc

@@ -53,26 +53,6 @@ SimpleClassDiagrams CoreFormalism {
             $
     }
 
-    SimpleAttribute TypeMapping {
-        constraint = $
-            String function constraint(model : Element, name : String):
-                Element self
-                self = model["model"][name]
-                if (has_value(self)):
-                    return "TypeMapping cannot have a value for root node!"!
-                Element keys
-                String key
-                keys = dict_keys(self)
-                while (read_nr_out(keys) > 0):
-                    key = set_pop(keys)
-                    if (bool_not(is_physical_string(key))):
-                        return ("Key on type mapping is not a string: " + cast_e2s(key))!
-                    elif (bool_not(is_physical_string(self[key]))):
-                        return ("Value on type mapping is not a string for key " + cast_e2s(key))!
-                return "OK"!
-            $
-    }
-
     Class User {
         name : String
         password : String
@@ -92,8 +72,9 @@ SimpleClassDiagrams CoreFormalism {
         permissions : Permissions
     }
 
+    Class TypeMapping : Model {}
+
     Association instanceOf (Model, Model) {
-        type_mapping : TypeMapping
     }
 
     Association owner (Model, User) {
@@ -112,18 +93,32 @@ SimpleClassDiagrams CoreFormalism {
 
     Class ActionLanguage : Transformation {}
 
-    Class ExternalTool : Transformation {}
-
     Class ManualOperation : Transformation {}
 
     Association transformInput (Model, Transformation) {
+        name : String
     }
     Association transformOutput (Transformation, Model) {
+        name : String
     }
 
     Association tracability (Model, Model) {
         type : String
     }
+
+    Association semantics (instanceOf, ActionLanguage) {
+        target_lower_cardinality = 1
+        target_upper_cardinality = 1
+    }
+    Association typing (instanceOf, TypeMapping) {
+        target_lower_cardinality = 1
+        target_upper_cardinality = 1
+    }
+
+    Class Service {
+        name : String
+        port : String
+    }
 }
 
 export CoreFormalism to models/CoreFormalism

+ 264 - 0
bootstrap/99_core.mvc

@@ -0,0 +1,264 @@
+import models/CoreFormalism as CF
+
+CF core {
+    Group admin_group {
+        name = "admin"
+    }
+
+    Group nobody {
+        name = "nobody"
+    }
+
+    User admin_user {
+        name = "admin"
+        admin = True
+        password = "c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8de9077ec"
+    }
+
+    ownedBy (admin_group, admin_user) {}
+    belongsTo (admin_user, admin_group) {}
+
+    Model SimpleClassDiagrams {
+        name = "SimpleClassDiagrams"
+        location = "models/SimpleClassDiagrams/model"
+        permissions = "221"
+    }
+
+    group (SimpleClassDiagrams, admin_group) {}
+    owner (SimpleClassDiagrams, admin_user) {}
+
+    TypeMapping TM_SimpleClassDiagrams {
+        name = "TM_SimpleClassDiagrams"
+        location = "models/SimpleClassDiagrams/type_mapping"
+        permissions = "221"
+    }
+
+    group (TM_SimpleClassDiagrams, admin_group) {}
+    owner (TM_SimpleClassDiagrams, admin_user) {}
+
+    Model TypeMapping {
+        name = "TypeMapping"
+        location = "models/TypeMapping/model"
+        permissions = "221"
+    }
+
+    group (TypeMapping, admin_group) {}
+    owner (TypeMapping, admin_user) {}
+
+    TypeMapping TM_TypeMapping {
+        name = "TM_TypeMapping"
+        location = "models/TypeMapping/type_mapping"
+        permissions = "221"
+    }
+
+    group (TM_TypeMapping, admin_group) {}
+    owner (TM_TypeMapping, admin_user) {}
+
+    Model Tracability {
+        name = "Tracability"
+        location = "models/Tracability/model"
+        permissions = "221"
+    }
+
+    group (Tracability, admin_group) {}
+    owner (Tracability, admin_user) {}
+
+    TypeMapping TM_Tracability{
+        name = "TM_Tracability"
+        location = "models/Tracability/type_mapping"
+        permissions = "221"
+    }
+
+    group (TM_Tracability, admin_group) {}
+    owner (TM_Tracability, admin_user) {}
+
+    Model ProcessModel {
+        name = "ProcessModel"
+        location = "models/ProcessModel/model"
+        permissions = "221"
+    }
+
+    group (ProcessModel, admin_group) {}
+    owner (ProcessModel, admin_user) {}
+
+    TypeMapping TM_ProcessModel {
+        name = "TM_ProcessModel"
+        location = "models/ProcessModel/type_mapping"
+        permissions = "221"
+    }
+
+    group (TM_ProcessModel, admin_group) {}
+    owner (TM_ProcessModel, admin_user) {}
+
+    Model ActionLanguage {
+        name = "ActionLanguage"
+        location = "models/ActionLanguage/model"
+        permissions = "221"
+    }
+
+    group (ActionLanguage, admin_group) {}
+    owner (ActionLanguage, admin_user) {}
+
+    TypeMapping TM_ActionLanguage {
+        name = "TM_ActionLanguage"
+        location = "models/ActionLanguage/type_mapping"
+        permissions = "221"
+    }
+
+    group (TM_ActionLanguage, admin_group) {}
+    owner (TM_ActionLanguage, admin_user) {}
+
+    Model ManualOperation {
+        name = "ManualOperation"
+        location = "models/ManualOperation/model"
+        permissions = "221"
+    }
+
+    group (ManualOperation, admin_group) {}
+    owner (ManualOperation, admin_user) {}
+
+    TypeMapping TM_ManualOperation {
+        name = "TM_ManualOperation"
+        location = "models/ManualOperation/type_mapping"
+        permissions = "221"
+    }
+
+    group (TM_ManualOperation, admin_group) {}
+    owner (TM_ManualOperation, admin_user) {}
+
+    ActionLanguage conformance_mv {
+        name = "conformance_mv"
+        location = "models/Conformance_MV/model"
+        permissions = "221"
+    }
+
+    group (conformance_mv, admin_group) {}
+    owner (conformance_mv, admin_user) {}
+
+    TypeMapping TM_conformance_mv {
+        name = "TM_conformance_mv"
+        location = "models/Conformance_MV/type_mapping"
+        permissions = "221"
+    }
+
+    group (TM_conformance_mv, admin_group) {}
+    owner (TM_conformance_mv, admin_user) {}
+
+    transformInput (conformance_mv, SimpleClassDiagrams) {
+        name = "model"
+    }
+    transformInput (conformance_mv, SimpleClassDiagrams) {
+        name = "metamodel"
+    }
+
+    Model CoreFormalism {
+        name = "CoreFormalism"
+        location = "models/CoreFormalism/model"
+        permissions = "221"
+    }
+
+    group (CoreFormalism, admin_group) {}
+    owner (CoreFormalism, admin_user) {}
+
+    TypeMapping TM_CoreFormalism {
+        name = "TM_CoreFormalism"
+        location = "models/CoreFormalism/type_mapping"
+        permissions = "221"
+    }
+
+    group (TM_CoreFormalism, admin_group) {}
+    owner (TM_CoreFormalism, admin_user) {}
+
+    Model Core {
+        name = "core"
+        location = "models/core/model"
+        permissions = "220"
+    }
+
+    group (Core, admin_group) {}
+    owner (Core, admin_user) {}
+
+    TypeMapping TM_Core {
+        name = "TM_core"
+        location = "models/core/type_mapping"
+        permissions = "220"
+    }
+
+    group (TM_Core, admin_group) {}
+    owner (TM_Core, admin_user) {}
+
+    Model bottom {
+        name = "bottom"
+        location = "models/bottom/model"
+        permissions = "221"
+    }
+
+    group (bottom, admin_group) {}
+    owner (bottom, admin_user) {}
+
+    TypeMapping TM_bottom {
+        name = "TM_bottom"
+        location = "models/bottom/type_mapping"
+        permissions = "221"
+    }
+
+    group (TM_bottom, admin_group) {}
+    owner (TM_bottom, admin_user) {}
+
+    instanceOf inst_SCD (SimpleClassDiagrams, SimpleClassDiagrams) {}
+    instanceOf inst_TM (TypeMapping, SimpleClassDiagrams) {}
+    instanceOf inst_trace (Tracability, SimpleClassDiagrams) {}
+    instanceOf inst_pm (ProcessModel, SimpleClassDiagrams) {}
+    instanceOf inst_al (ActionLanguage, SimpleClassDiagrams) {}
+    instanceOf inst_man (ManualOperation, SimpleClassDiagrams) {}
+    instanceOf inst_conf (conformance_mv, ActionLanguage) {}
+    instanceOf inst_cf (CoreFormalism, SimpleClassDiagrams) {}
+    instanceOf inst_core (Core, CoreFormalism) {}
+    instanceOf inst_bottom (bottom, SimpleClassDiagrams) {}
+
+    instanceOf TM_inst_SCD (TM_SimpleClassDiagrams, TypeMapping) {}
+    instanceOf TM_inst_TM (TM_TypeMapping, TypeMapping) {}
+    instanceOf TM_inst_trace (TM_Tracability, TypeMapping) {}
+    instanceOf TM_inst_pm (TM_ProcessModel, TypeMapping) {}
+    instanceOf TM_inst_al (TM_ActionLanguage, TypeMapping) {}
+    instanceOf TM_inst_man (TM_ManualOperation, TypeMapping) {}
+    instanceOf TM_inst_conf (TM_conformance_mv, TypeMapping) {}
+    instanceOf TM_inst_cf (TM_CoreFormalism, TypeMapping) {}
+    instanceOf TM_inst_core (TM_Core, TypeMapping) {}
+    instanceOf TM_inst_bottom (TM_bottom, TypeMapping) {}
+
+    typing (inst_SCD, TM_SimpleClassDiagrams) {}
+    typing (inst_TM, TM_TypeMapping) {}
+    typing (inst_trace, TM_Tracability) {}
+    typing (inst_pm, TM_ProcessModel) {}
+    typing (inst_al, TM_ActionLanguage) {}
+    typing (inst_man, TM_ManualOperation) {}
+    typing (inst_conf, TM_conformance_mv) {}
+    typing (inst_cf, TM_CoreFormalism) {}
+    typing (inst_core, TM_Core) {}
+    typing (inst_bottom, TM_bottom) {}
+
+    semantics (inst_SCD, conformance_mv) {}
+    semantics (inst_TM, conformance_mv) {}
+    semantics (inst_trace, conformance_mv) {}
+    semantics (inst_pm, conformance_mv) {}
+    semantics (inst_al, conformance_mv) {}
+    semantics (inst_man, conformance_mv) {}
+    semantics (inst_conf, conformance_mv) {}
+    semantics (inst_cf, conformance_mv) {}
+    semantics (inst_core, conformance_mv) {}
+    semantics (inst_bottom, conformance_mv) {}
+
+    semantics (TM_inst_SCD, conformance_mv) {}
+    semantics (TM_inst_TM, conformance_mv) {}
+    semantics (TM_inst_trace, conformance_mv) {}
+    semantics (TM_inst_pm, conformance_mv) {}
+    semantics (TM_inst_al, conformance_mv) {}
+    semantics (TM_inst_man, conformance_mv) {}
+    semantics (TM_inst_conf, conformance_mv) {}
+    semantics (TM_inst_cf, conformance_mv) {}
+    semantics (TM_inst_core, conformance_mv) {}
+    semantics (TM_inst_bottom, conformance_mv) {}
+}
+
+export core to models/core

+ 1 - 17
bootstrap/bootstrap.py

@@ -25,16 +25,12 @@ def bootstrap():
                     "integer_subtraction": ["Integer", "Integer", "Integer"],
                     "integer_multiplication": ["Integer", "Integer", "Integer"],
                     "integer_division": ["Integer", "Integer", "Integer"],
-                    "integer_gt": ["Boolean", "Integer", "Integer"],
                     "integer_lt": ["Boolean", "Integer", "Integer"],
-                    "integer_neg": ["Integer", "Integer"],
                     "float_addition": ["Float", "Float", "Float"],
                     "float_subtraction": ["Float", "Float", "Float"],
                     "float_multiplication": ["Float", "Float", "Float"],
                     "float_division": ["Float", "Float", "Float"],
-                    "float_gt": ["Boolean", "Float", "Float"],
                     "float_lt": ["Boolean", "Float", "Float"],
-                    "float_neg": ["Float", "Float"],
                     "bool_and": ["Boolean", "Boolean", "Boolean"],
                     "bool_or": ["Boolean", "Boolean", "Boolean"],
                     "bool_not": ["Boolean", "Boolean"],
@@ -43,7 +39,6 @@ def bootstrap():
                     "string_len": ["Integer", "String"],
                     "string_split": ["Element", "String", "String"],
                     "value_eq":  ["Boolean", "Element", "Element"],
-                    "value_neq": ["Boolean", "Element", "Element"],
                     "cast_i2f": ["Float", "Integer"],
                     "cast_i2s": ["String", "Integer"],
                     "cast_i2b": ["Boolean", "Integer"],
@@ -60,28 +55,17 @@ def bootstrap():
                     "cast_a2s": ["String", "Action"],
                     "cast_v2s": ["String", "Element"],
                     "cast_id2s": ["String", "Element"],
-                    "list_read": ["Element", "Element", "Integer"],
-                    "list_append": ["Element", "Element", "Element"],
                     "list_insert": ["Element", "Element", "Integer", "Element"],
                     "list_delete": ["Element", "Element", "Integer"],
-                    "list_len": ["Integer", "Element"],
-                    "dict_add": ["Element", "Element", "Element", "Element"],
                     "dict_add_fast": ["Element", "Element", "Element", "Element"],
                     "dict_delete": ["Element", "Element", "Element"],
                     "dict_delete_node": ["Element", "Element", "Element"],
                     "dict_read": ["Element", "Element", "Element"],
                     "dict_read_edge": ["Element", "Element", "Element"],
                     "dict_read_node": ["Element", "Element", "Element"],
-                    "dict_len": ["Integer", "Element"],
                     "dict_in": ["Boolean", "Element", "Element"],
                     "dict_in_node": ["Boolean", "Element", "Element"],
                     "dict_keys": ["Element", "Element"],
-                    "set_add": ["Element", "Element", "Element"],
-                    "set_pop": ["Element", "Element"],
-                    "set_remove": ["Element", "Element", "Element"],
-                    "set_remove_node": ["Element", "Element", "Element"],
-                    "set_in": ["Boolean", "Element", "Element"],
-                    "set_in_node": ["Boolean", "Element", "Element"],
                     "is_physical_int": ["Boolean", "Element"],
                     "is_physical_boolean": ["Boolean", "Element"],
                     "is_physical_string": ["Boolean", "Element"],
@@ -99,12 +83,12 @@ def bootstrap():
                     "read_edge_dst": ["Element", "Element"],
                     "delete_element": ["Element", "Element"],
                     "element_eq": ["Boolean", "Element", "Element"],
-                    "element_neq": ["Boolean", "Element", "Element"],
                     "read_root": ["Element"],
                     "read_taskroot": ["Element"],
                     "log": ["String", "String"],
                     "time": ["Float"],
                     "hash": ["String", "String"],
+                    "__sleep": ["Float", "Float", "Boolean"],
                 }
 
     jit_primitives = {

+ 8 - 0
bootstrap/bottom.mvc

@@ -0,0 +1,8 @@
+import models/SimpleClassDiagrams as SCD
+
+SCD bottom{
+    Class Node {}
+    Association Edge : Node (Node, Node) {}
+}
+
+export bottom to models/bottom

+ 49 - 0
bootstrap/compiler.alc

@@ -0,0 +1,49 @@
+include "primitives.alh"
+include "services.alh"
+include "constructors.alh"
+include "modelling.alh"
+
+Element function generic_compile(code : String, port : String):
+	comm_set(port, code)
+	
+	String response
+	response = comm_get(port)
+	if (response == "OK"):
+		Element lst
+
+		lst = comm_get_list(port)
+
+		comm_close(port)
+		return lst!
+	else:
+		log("Compilation error: " + response)
+		comm_close(port)
+		return read_root()!
+
+Element function compile_code(code : String):
+	String port
+	port = comm_connect("compiler")
+	comm_set(port, "code")
+
+	Element list
+	list = generic_compile(code, port)
+
+	if (element_eq(list, read_root())):
+		return read_root()!
+
+	else:
+		return construct_function_list(list)!
+
+Element function compile_model(code : String, model : Element):
+	String port
+	port = comm_connect("compiler")
+	comm_set(port, "model")
+
+	Element list
+	list = generic_compile(code, port)
+
+	if (element_eq(list, read_root())):
+		return read_root()!
+
+	else:
+		return construct_model_list(model, list)!

+ 85 - 0
bootstrap/conformance_finding.alc

@@ -0,0 +1,85 @@
+include "primitives.alh"
+include "object_operations.alh"
+include "typing.alh"
+
+Boolean function find_type_mapping(model : Element):
+	// Finds a correct type mapping for the provided model (with partial type mapping)
+	// We go through several phases:
+	//   1) remove elements from type mapping that are not in the model or metamodel
+	//   2) find a mapping based on the current partial mapping
+	//   3) (optional) verify that the mapping is correct with conformance checking
+	// Returns True if the type mapping was altered
+
+	// Start of with some initialization
+	Element tm
+	Element elems
+	String elem
+
+	tm = get_type_mapping_as_dict(model)
+
+	// 1) remove elements from type mapping that are not in the model or metamodel
+	elems = dict_keys(tm)
+	while (set_len(elems) > 0):
+		elem = set_pop(elems)
+		if (bool_not(dict_in(model["model"], elem))):
+			// Remove the key, as the model does not contain the element anymore
+			dict_delete(tm, elem)
+		else:
+			if (bool_not(dict_in(model["metamodel"]["model"], tm[elem]))):
+				// Remove the key, as the metamodel does not contain the type anymore
+				dict_delete(tm, elem)
+		
+	// 2) find a mapping based on the current partial mapping, but only if it is not yet complete
+	// TODO this must be expanded for other things than trivial metamodels!
+	if (dict_len(model["model"]) > dict_len(tm)):
+		// log("Model is incompletely typed!")
+		// log("Model has: " + set_to_string(dict_keys(model["model"])))
+		// log("Type mapping has: " + set_to_string(dict_keys(tm)))
+		// log("Missing: " + set_to_string(set_difference(dict_keys(model["model"]), dict_keys(tm))))
+
+		// TODO for now, this only returns something for a simple case, where the MM has one edge, and one node
+		//      and it makes the assumption that SCD is the M3 level...
+
+		// First find the name of the edge and node elements
+		Element elems
+		String elem
+
+		String node_element
+		String edge_element
+		node_element = read_root()
+		edge_element = read_root()
+
+		elems = dict_keys(model["metamodel"]["model"])
+		while (set_len(elems) > 0):
+			elem = set_pop(elems)
+
+			if (bool_not(is_edge(model["metamodel"]["model"][elem]))):
+				if (element_neq(node_element, read_root())):
+					return False!
+				node_element = elem
+			else:
+				// Is an edge, but might be the inheritance link...
+				if (read_type(model["metamodel"], elem) != "Inheritance"):
+					// Is not the inheritance link
+					if (element_neq(edge_element, read_root())):
+						return False!
+					edge_element = elem
+
+		if (bool_or(element_eq(node_element, read_root()), element_eq(edge_element, read_root()))):
+			return False!
+
+		// Now we have bot an edge_element and node_element of the metamodel
+		// Now just trivially bind all elements!
+		elems = dict_keys(model["model"])
+		while (set_len(elems) > 0):
+			elem = set_pop(elems)
+
+			if (is_edge(elem)):
+				retype(model, elem, edge_element)
+			else:
+				retype(model, elem, node_element)
+
+	// 3) (optional) verify that the mapping is correct with conformance checking
+	// TODO
+	
+	return True!

+ 31 - 53
bootstrap/conformance_scd.alc

@@ -3,12 +3,25 @@ include "library.alh"
 include "object_operations.alh"
 include "constructors.alh"
 include "modelling.alh"
+include "typing.alh"
+
+Boolean function wrap_conformance(model : Element):
+	String result
+	result = conformance_scd(model)
+	output("Success: " + result)
+	if (result == "OK"):
+		return True!
+	else:
+		return False!
 
 Boolean function is_direct_instance(model : Element, instance : String, type : String):
 	// Just check whether or not the type mapping specifies the type as the type of the instance
-	return value_eq(model["type_mapping"][instance], type)!
+	return (read_type(model, instance) == type)!
 
 Boolean function is_nominal_instance(model : Element, instance : String, type : String):
+	if (read_type(model, instance) == type):
+		return True!
+
 	if (bool_not(dict_in(model["metamodel"]["model"], type))):
 		// type is not even in the specified metamodel, so this will never work
 		return False!
@@ -17,14 +30,11 @@ Boolean function is_nominal_instance(model : Element, instance : String, type :
 		// type is an edge, but we aren't
 		return False!
 
-	if (bool_not(dict_in(model["type_mapping"], instance))):
+	if (element_eq(read_type(model, instance), read_root())):
 		// doesn't even have a type
 		return False!
 
-	if (value_eq(model["type_mapping"][instance], type)):
-		return True!
-
-	return is_nominal_subtype(model["metamodel"], model["type_mapping"][instance], type)!
+	return is_nominal_subtype(model["metamodel"], read_type(model, instance), type)!
 
 Boolean function is_nominal_subtype(metamodel : Element, subclass : String, superclass : String):
 	if (element_eq(metamodel["model"][subclass], metamodel["model"][superclass])):
@@ -53,10 +63,10 @@ Element function precompute_cardinalities(model : Element):
 	metamodel = model["metamodel"]
 	keys = allInstances(metamodel, "Association")
 
-	cardinalities = create_node()
-	while (0 < list_len(keys)):
+	cardinalities = dict_create()
+	while (0 < set_len(keys)):
 		key = set_pop(keys)
-		tmp_dict = create_node()
+		tmp_dict = dict_create()
 		slc = read_attribute(metamodel, key, "source_lower_cardinality")
 		suc = read_attribute(metamodel, key, "source_upper_cardinality")
 		tlc = read_attribute(metamodel, key, "target_lower_cardinality")
@@ -71,13 +81,13 @@ Element function precompute_cardinalities(model : Element):
 		if (element_neq(tuc, read_root())):
 			dict_add_fast(tmp_dict, "tuc", tuc)
 
-		if (list_len(tmp_dict) > 0):
+		if (dict_len(tmp_dict) > 0):
 			dict_add_fast(cardinalities, key, tmp_dict)
 
 	keys = allInstances(metamodel, "AttributeLink")
-	while (0 < list_len(keys)):
+	while (0 < set_len(keys)):
 		key = set_pop(keys)
-		tmp_dict = create_node()
+		tmp_dict = dict_create()
 
 		// Attributes always have 1 max
 		dict_add_fast(tmp_dict, "tuc", 1)
@@ -89,7 +99,7 @@ Element function precompute_cardinalities(model : Element):
 		else:
 			dict_add_fast(tmp_dict, "tlc", 1)
 
-		if (list_len(tmp_dict) > 0):
+		if (dict_len(tmp_dict) > 0):
 			dict_add_fast(cardinalities, key, tmp_dict)
 
 	return cardinalities!
@@ -120,16 +130,16 @@ String function conformance_scd(model : Element):
 	reverse_m = make_reverse_dictionary(model["model"])
 	reverse_mm = make_reverse_dictionary(model["metamodel"]["model"])
 
-	spo_cache = create_node()
-	spi_cache = create_node()
+	spo_cache = dict_create()
+	spi_cache = dict_create()
 
 	// Load in variables
 	scd = import_node("models/SimpleClassDiagrams")
 	metamodel = model["metamodel"]
-	typing = model["type_mapping"]
+	typing = get_type_mapping_as_dict(model)
 
 	// Create dictionary with all associations and allowed cardinalities
-	if (list_len(model["model"]) > 0):
+	if (dict_len(model["model"]) > 0):
 		cardinalities = precompute_cardinalities(model)
 
 		// Iterate over each element of the model, finding out whether everything is fine
@@ -236,7 +246,7 @@ String function conformance_scd(model : Element):
 	mm_model = metamodel["model"]
 
 	metamodel_keys = dict_keys(mm_model)
-	while (read_nr_out(metamodel_keys) > 0):
+	while (set_len(metamodel_keys) > 0):
 		metamodel_element = set_pop(metamodel_keys)
 
 		// Lower multiplicities
@@ -260,11 +270,11 @@ String function conformance_scd(model : Element):
 	String complex_type
 	String result
 	all_complex_types = allInstances(model["metamodel"]["metamodel"], "ComplexAttribute")
-	while (read_nr_out(all_complex_types) > 0):
+	while (set_len(all_complex_types) > 0):
 		complex_type = set_pop(all_complex_types)
 		complex_instances = allInstances(model, complex_type)
 
-		while (read_nr_out(complex_instances) > 0):
+		while (set_len(complex_instances) > 0):
 			complex_instance = set_pop(complex_instances)
 
 			complex_type = read_attribute(model["metamodel"], read_type(model, complex_instance), "type")
@@ -279,7 +289,7 @@ String function conformance_scd(model : Element):
 	Element func
 
 	global_constraints = allInstances(model, "GlobalConstraint")
-	while (read_nr_out(global_constraints) > 0):
+	while (set_len(global_constraints) > 0):
 		constraint = set_pop(global_constraints)
 		func = get_func_AL_model(import_node(read_attribute(model, constraint, "global_constraint")))
 		result = func(model)
@@ -307,37 +317,5 @@ Element function set_model_constraints(model : Element, func : Element):
 	dict_add_fast(model, "constraints", func)
 	return model!
 
-Element function generate_bottom_type_mapping(model : Element):
-	Element mm
-	mm = model["metamodel"]["model"]
-	dict_delete(model, "type_mapping")
-	Element tm
-	tm = create_node()
-	dict_add_fast(model, "type_mapping", tm)
-	
-	// Iterate over every element
-	Element elem_keys
-	String elem
-
-	elem_keys = dict_keys(model["model"])
-	while (read_nr_out(elem_keys) > 0):
-		elem = set_pop(elem_keys)
-
-		if (is_edge(model["model"][elem])):
-			dict_add_fast(tm, elem, "Edge")
-		else:
-			dict_add_fast(tm, elem, "Node")
-
-	return model!
-
 String function model_info(model : Element, name : String):
 	return name!
-	// For more detailed information
-	String result
-	result = ""
-	result = (result + "\nModel name: ") + name
-	result = (result + "\nType: ") + cast_v2s(model["type_mapping"][name])
-	result = (result + "\nValue: ") + cast_v2s(model["model"][name])
-	result = (result + "\nSource: ") + cast_v2s(reverseKeyLookup(model["model"], read_edge_src(model["model"][name])))
-	result = (result + "\nDestination: ") + cast_v2s(reverseKeyLookup(model["model"], read_edge_dst(model["model"][name])))
-	return result!

+ 168 - 116
bootstrap/constructors.alc

@@ -3,11 +3,24 @@ include "conformance_scd.alh"
 include "library.alh"
 include "io.alh"
 include "modelling.alh"
+include "utils.alh"
 
 Element while_stack = ?
 Element variable_map = ?
 
 Element function construct_function():
+	Integer len
+	Element list
+
+	len = input()
+	list = list_create()
+
+	while (list_len(list) < len):
+		list_append(list, input())
+
+	return construct_function_list(list)!
+
+Element function construct_function_list(list : Element):
 	String command
 	Element result
 	Element main_function
@@ -15,29 +28,31 @@ Element function construct_function():
 	Element prev_element
 	Element first_element
 
+	list = list_reverse(list)
+
 	// Initialize variables
 	prev_element = read_root()
 	main_function = read_root()
 
 	// Clear global variables
-	while_stack = create_node()
-	variable_map = create_node()
+	while_stack = list_create()
+	variable_map = dict_create()
 
 	continue = True
 	while (continue):
-		command = input()
+		command = list_pop_final(list)
 		if (command == "global"):
-			result = construct_global()
+			result = construct_global(list)
 		elif (command == "funcdef"):
-			result = construct_funcdef(False)
+			result = construct_funcdef(False, list)
 		elif (command == "mutable_funcdef"):
-			result = construct_funcdef(True)
+			result = construct_funcdef(True, list)
 		else:
 			log("ERROR (1): did not understand command " + cast_e2s(command))
 			output("ERROR: compiled code not understood: " + cast_e2s(command))
 			return read_root()!
 
-		continue = input()
+		continue = list_pop_final(list)
 		if (prev_element != read_root()):
 			dict_add_fast(prev_element, "next", result["start"])
 		else:
@@ -61,59 +76,66 @@ Element function construct_function():
 
 	// Overwrite the main function with our declaration function
 	prev_element = main_function["body"]
-	log("Got main function V: " + cast_e2s(main_function))
-	log("Got main function S: " + dict_to_string(main_function))
 	dict_delete(main_function, "body")
 	dict_add_fast(main_function, "body", first_element)
 	dict_add_fast(result["end"], "next", prev_element)
 	
 	return main_function!
 
-Action function construct_global():
+Action function construct_global(list : Element):
 	Action this_element
 	String declared_element
 	String op
 
 	this_element = create_value(!global)
-	declared_element = input()
+	declared_element = list_pop_final(list)
 	dict_add_fast(this_element, "var", declared_element)
 
-	// Defines
-	Action assign
-	Action resolve
-	Action value
-	assign = create_value(!assign)
-	dict_add_fast(this_element, "next", assign)
-	resolve = create_value(!resolve)
-	dict_add_fast(assign, "var", resolve)
-	dict_add_fast(resolve, "var", declared_element)
-	op = input()
-	if (op == "deref"):
-		value = create_value(!constant)
-		dict_add_fast(value, "node", import_node(input()))
-	elif (op == "empty"):
-		value = create_value(!call)
-		Element res
-		Element acc
-		res = create_value(!resolve)
-		acc = create_value(!access)
-		dict_add_fast(value, "func", acc)
-		dict_add_fast(acc, "var", res)
-		dict_add_fast(res, "var", "create_node")
-	elif (op == "const"):
-		value = create_value(!constant)
-		dict_add_fast(value, "node", input())
-	dict_add_fast(assign, "value", value)
-
-	Element result
-	result = create_node()
-	dict_add_fast(result, "name", "")
-	dict_add_fast(result, "instruction", this_element)
-	dict_add_fast(result, "start", this_element)
-	dict_add_fast(result, "end", assign)
-	return result!
-
-Action function construct_funcdef(mutable : Boolean):
+	op = list_pop_final(list)
+	if (op != "none"):
+		// Defines
+		Action assign
+		Action resolve
+		Action value
+		assign = create_value(!assign)
+		dict_add_fast(this_element, "next", assign)
+		resolve = create_value(!resolve)
+		dict_add_fast(assign, "var", resolve)
+		dict_add_fast(resolve, "var", declared_element)
+		if (op == "deref"):
+			value = create_value(!constant)
+			dict_add_fast(value, "node", import_node(list_pop_final(list)))
+		elif (op == "empty"):
+			value = create_value(!call)
+			Element res
+			Element acc
+			res = create_value(!resolve)
+			acc = create_value(!access)
+			dict_add_fast(value, "func", acc)
+			dict_add_fast(acc, "var", res)
+			dict_add_fast(res, "var", "create_node")
+		elif (op == "const"):
+			value = create_value(!constant)
+			dict_add_fast(value, "node", list_pop_final(list))
+		dict_add_fast(assign, "value", value)
+
+		Element result
+		result = dict_create()
+		dict_add_fast(result, "name", "")
+		dict_add_fast(result, "instruction", this_element)
+		dict_add_fast(result, "start", this_element)
+		dict_add_fast(result, "end", assign)
+		return result!
+	else:
+		Element result
+		result = dict_create()
+		dict_add_fast(result, "name", "")
+		dict_add_fast(result, "instruction", this_element)
+		dict_add_fast(result, "start", this_element)
+		dict_add_fast(result, "end", this_element)
+		return result!
+
+Action function construct_funcdef(mutable : Boolean, list : Element):
 	Action assign
 	Action resolve
 	Action constant
@@ -127,7 +149,7 @@ Action function construct_funcdef(mutable : Boolean):
 	assign = create_value(!assign)
 	resolve = create_value(!resolve)
 	constant = create_value(!constant)
-	name = input()
+	name = list_pop_final(list)
 	if (dict_in(variable_map, name)):
 		formal = dict_read(variable_map, name)
 	else:
@@ -146,7 +168,7 @@ Action function construct_funcdef(mutable : Boolean):
 		dict_add_fast(func, "mutable", create_node())
 
 	Integer nrParams
-	nrParams = input()
+	nrParams = list_pop_final(list)
 	Integer counter
 	counter = 0
 	Element param
@@ -158,100 +180,97 @@ Action function construct_funcdef(mutable : Boolean):
 		param = create_node()
 		dict_add_fast(params, string_get(arg_names_decl, counter), param)
 		dict_add_fast(param, "name", string_get(arg_names_decl, counter))
-		dict_add_fast(variable_map, input(), param)
+		dict_add_fast(variable_map, list_pop_final(list), param)
 		// Output each parameter in turn
 		counter = counter + 1
 
 	// Now add the body
-	dict_add_fast(func, "body", construct_unknown())
+	dict_add_fast(func, "body", construct_unknown(list))
 
 	Element result
-	result = create_node()
+	result = dict_create()
 	dict_add_fast(result, "name", name)
 	dict_add_fast(result, "instruction", func)
 	dict_add_fast(result, "start", declare)
 	dict_add_fast(result, "end", assign)
 	return result!
 
-Element function construct_unknown():
+Element function construct_unknown(list : Element):
 	String elem
 	Element new_model
 	Element new_model_model
-	elem = input()
+	elem = list_pop_final(list)
 
 	if (elem == "if"):
-		return construct_if()!
+		return construct_if(list)!
 	elif (elem == "while"):
-		return construct_while()!
+		return construct_while(list)!
 	elif (elem == "access"):
-		return construct_access()!
+		return construct_access(list)!
 	elif (elem == "resolve"):
-		return construct_resolve()!
+		return construct_resolve(list)!
 	elif (elem == "assign"):
-		return construct_assign()!
+		return construct_assign(list)!
 	elif (elem == "call"):
-		return construct_call()!
+		return construct_call(list)!
 	elif (elem == "return"):
-		return construct_return()!
+		return construct_return(list)!
 	elif (elem == "const"):
-		return construct_const()!
+		return construct_const(list)!
 	elif (elem == "declare"):
-		return construct_declare()!
+		return construct_declare(list)!
 	elif (elem == "output"):
-		return construct_output()!
+		return construct_output(list)!
 	elif (elem == "input"):
-		return construct_input()!
+		return construct_input(list)!
 	elif (elem == "deref"):
-		return construct_deref()!
+		return construct_deref(list)!
 	elif (elem == "break"):
-		return construct_break()!
+		return construct_break(list)!
 	elif (elem == "continue"):
-		return construct_continue()!
-	elif (elem == "model"):
-		construct_model()
-		return construct_unknown()!
+		return construct_continue(list)!
 	else:
 		log("ERROR (2): did not understand command " + cast_e2s(elem))
 		output("ERROR: compiled code not understood: " + cast_e2s(elem))
 		return read_root()!
 
-Action function construct_if():
+Action function construct_if(list : Element):
 	Action this_element
 	this_element = create_value(!if)
-	dict_add_fast(this_element, "cond", construct_unknown())
-	dict_add_fast(this_element, "then", construct_unknown())
-	if (input()):
-		dict_add_fast(this_element, "else", construct_unknown())
-	if (input()):
-		dict_add_fast(this_element, "next", construct_unknown())
+	dict_add_fast(this_element, "cond", construct_unknown(list))
+	dict_add_fast(this_element, "then", construct_unknown(list))
+	if (list_pop_final(list)):
+		dict_add_fast(this_element, "else", construct_unknown(list))
+	if (list_pop_final(list)):
+		dict_add_fast(this_element, "next", construct_unknown(list))
 	return this_element!
 
-Action function construct_while():
+Action function construct_while(list : Element):
 	Action this_element
 	this_element = create_value(!while)
-	dict_add_fast(this_element, "cond", construct_unknown())
+	dict_add_fast(this_element, "cond", construct_unknown(list))
 
 	list_append(while_stack, this_element)
-	dict_add_fast(this_element, "body", construct_unknown())
+	dict_add_fast(this_element, "body", construct_unknown(list))
 	list_delete(while_stack, list_len(while_stack) - 1)
 
-	if (input()):
-		dict_add_fast(this_element, "next", construct_unknown())
+	if (list_pop_final(list)):
+		dict_add_fast(this_element, "next", construct_unknown(list))
 	return this_element!
 
-Action function construct_access():
+Action function construct_access(list : Element):
 	Action this_element
 	this_element = create_value(!access)
-	dict_add_fast(this_element, "var", construct_unknown())
+	dict_add_fast(this_element, "var", construct_unknown(list))
 	return this_element!
 
-Action function construct_resolve():
+Action function construct_resolve(list : Element):
 	Action this_element
 	Element linked_element
 	String name
 
 	this_element = create_value(!resolve)
-	name = input()
+	name = list_pop_final(list)
 	if dict_in(variable_map, name):
 		linked_element = variable_map[name]
 	else:
@@ -259,22 +278,22 @@ Action function construct_resolve():
 	dict_add_fast(this_element, "var", linked_element)
 	return this_element!
 
-Action function construct_assign():
+Action function construct_assign(list : Element):
 	Action this_element
 	this_element = create_value(!assign)
-	dict_add_fast(this_element, "var", construct_unknown())
-	dict_add_fast(this_element, "value", construct_unknown())
-	if (input()):
-		dict_add_fast(this_element, "next", construct_unknown())
+	dict_add_fast(this_element, "var", construct_unknown(list))
+	dict_add_fast(this_element, "value", construct_unknown(list))
+	if (list_pop_final(list)):
+		dict_add_fast(this_element, "next", construct_unknown(list))
 	return this_element!
 
-Action function construct_call():
+Action function construct_call(list : Element):
 	Action this_element
 	this_element = create_value(!call)
-	dict_add_fast(this_element, "func", construct_unknown())
+	dict_add_fast(this_element, "func", construct_unknown(list))
 
 	Integer nrParams
-	nrParams = input()
+	nrParams = list_pop_final(list)
 	Integer counter
 	counter = 0
 
@@ -287,7 +306,7 @@ Action function construct_call():
 		param = create_node()
 
 		dict_add_fast(param, "name", string_get(arg_names_call, counter))
-		dict_add_fast(param, "value", construct_unknown())
+		dict_add_fast(param, "value", construct_unknown(list))
 
 		if (counter == 0):
 			dict_add_fast(this_element, "params", param)
@@ -300,26 +319,26 @@ Action function construct_call():
 	if (nrParams > 0):
 		dict_add_fast(this_element, "last_param", prev_param)
 
-	if (input()):
-		dict_add_fast(this_element, "next", construct_unknown())
+	if (list_pop_final(list)):
+		dict_add_fast(this_element, "next", construct_unknown(list))
 	return this_element!
 
-Action function construct_return():
-	if (input()):
+Action function construct_return(list : Element):
+	if (list_pop_final(list)):
 		Action this_element
 		this_element = create_value(!return)
-		dict_add_fast(this_element, "value", construct_unknown())
+		dict_add_fast(this_element, "value", construct_unknown(list))
 		return this_element!
 	else:
 		return create_value(!return)!
 
-Action function construct_const():
+Action function construct_const(list : Element):
 	Action this_element
 	this_element = create_value(!constant)
-	dict_add_fast(this_element, "node", input())
+	dict_add_fast(this_element, "node", list_pop_final(list))
 	return this_element!
 
-Action function construct_declare():
+Action function construct_declare(list : Element):
 	Action this_element
 	Element declared_element
 	String name
@@ -327,38 +346,71 @@ Action function construct_declare():
 	this_element = create_value(!declare)
 	declared_element = create_node()
 	dict_add_fast(this_element, "var", declared_element)
-	name = input()
+	name = list_pop_final(list)
 	dict_add_fast(variable_map, name, declared_element)
-	if (input()):
-		dict_add_fast(this_element, "next", construct_unknown())
+
+	// Assign value
+	String op
+	op = list_pop_final(list)
+	if (op != "none"):
+		Action assign
+		Action resolve
+		Action value
+		assign = create_value(!assign)
+		dict_add_fast(this_element, "next", assign)
+		resolve = create_value(!resolve)
+		dict_add_fast(assign, "var", resolve)
+		dict_add_fast(resolve, "var", declared_element)
+		if (op == "deref"):
+			value = create_value(!constant)
+			dict_add_fast(value, "node", import_node(list_pop_final(list)))
+		elif (op == "empty"):
+			value = create_value(!call)
+			Element res
+			Element acc
+			res = create_value(!resolve)
+			acc = create_value(!access)
+			dict_add_fast(value, "func", acc)
+			dict_add_fast(acc, "var", res)
+			dict_add_fast(res, "var", "create_node")
+		elif (op == "const"):
+			value = create_value(!constant)
+			dict_add_fast(value, "node", list_pop_final(list))
+		dict_add_fast(assign, "value", value)
+
+		if (list_pop_final(list)):
+			dict_add_fast(assign, "next", construct_unknown(list))
+	else:
+		if (list_pop_final(list)):
+			dict_add_fast(this_element, "next", construct_unknown(list))
 	return this_element!
 
-Action function construct_input():
+Action function construct_input(list : Element):
 	Action this_element
 	this_element = create_value(!input)
 	return this_element!
 
-Action function construct_output():
+Action function construct_output(list : Element):
 	Action this_element
 	this_element = create_value(!output)
-	dict_add_fast(this_element, "value", construct_unknown())
-	if (input()):
-		dict_add_fast(this_element, "next", construct_unknown())
+	dict_add_fast(this_element, "value", construct_unknown(list))
+	if (list_pop_final(list)):
+		dict_add_fast(this_element, "next", construct_unknown(list))
 	return this_element!
 
-Action function construct_deref():
+Action function construct_deref(list : Element):
 	Action this_element
 	this_element = create_value(!constant)
-	dict_add_fast(this_element, "node", import_node(input()))
+	dict_add_fast(this_element, "node", import_node(list_pop_final(list)))
 	return this_element!
 
-Action function construct_break():
+Action function construct_break(list : Element):
 	Action this_element
 	this_element = create_value(!break)
 	dict_add_fast(this_element, "while", while_stack[list_len(while_stack) - 1])
 	return this_element!
 
-Action function construct_continue():
+Action function construct_continue(list : Element):
 	Action this_element
 	this_element = create_value(!continue)
 	dict_add_fast(this_element, "while", while_stack[list_len(while_stack) - 1])

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 906 - 753
bootstrap/core_algorithm.alc


+ 4 - 0
bootstrap/initial_code_manager.alc

@@ -1,4 +1,5 @@
 include "bootstrap/primitives.alc"
+include "bootstrap/semi_primitives.alc"
 include "task_manager.alh"
 
 Void function __main():
@@ -13,5 +14,8 @@ Void function __main():
 	exec(root["bootstrap/modelling.alc"]["initializers"])
 	exec(root["bootstrap/task_manager.alc"]["initializers"])
 	exec(root["bootstrap/core_algorithm.alc"]["initializers"])
+	exec(root["bootstrap/utils.alc"]["initializers"])
+	exec(root["bootstrap/io.alc"]["initializers"])
+	exec(root["bootstrap/typing.alc"]["initializers"])
 	task_management()
 	return!

+ 8 - 1
bootstrap/initial_code_task.alc

@@ -1,5 +1,6 @@
 include "bootstrap/primitives.alc"
-include "bootstrap/core_algorithm.alc"
+include "bootstrap/semi_primitives.alc"
+include "core_algorithm.alh"
 
 Void mutable function __main():
 	Element root
@@ -17,5 +18,11 @@ Void mutable function __main():
 	exec(root["bootstrap/transform.alc"]["initializers"])
 	exec(root["bootstrap/conformance_scd.alc"]["initializers"])
 	exec(root["bootstrap/random.alc"]["initializers"])
+	exec(root["bootstrap/utils.alc"]["initializers"])
+	exec(root["bootstrap/services.alc"]["initializers"])
+	exec(root["bootstrap/io.alc"]["initializers"])
+	exec(root["bootstrap/conformance_finding.alc"]["initializers"])
+	exec(root["bootstrap/typing.alc"]["initializers"])
+	exec(root["bootstrap/compiler.alc"]["initializers"])
 	new_task()
 	return!

+ 36 - 0
bootstrap/io.alc

@@ -0,0 +1,36 @@
+include "io.alh"
+include "primitives.alh"
+
+// Placeholder for internal functions
+Element function __input()
+Void function __output(value : Element)
+
+Element function input():
+	while (bool_not(has_input())):
+		interruptable_sleep(0.5)
+	
+	Element inp
+	inp = __input()
+	return inp!
+
+Void function output(value : Element):
+	__output(value)
+	return!
+
+Element function input_timeout(timeout : Float):
+	Float start
+	start = time()
+
+	// Do this first, such that we will always get at least the chance to push input in
+	if (has_input()):
+		return input()!
+
+	// Now just try this again from time to time
+	while (time() - start < timeout):
+		if (has_input()):
+			return input()!
+		else:
+			// Nothing to do, we should yield...
+			interruptable_sleep(0.1)
+
+	return read_root()!

+ 2 - 2
bootstrap/library.alc

@@ -12,8 +12,8 @@ Element function export_node(model_name : String, model_reference : Element):
 	while(counter_i < length):
 		if (bool_not(dict_in(current, splitted[counter_i]))):
 			// Create the new node
-			dict_add(current, splitted[counter_i], create_node())
-			dict_add(current[splitted[counter_i]], "__hierarchy_node", create_node())
+			dict_add(current, splitted[counter_i], dict_create())
+			dict_add(current[splitted[counter_i]], "__hierarchy_node", dict_create())
 
 		// Read out newly created element
 		current = current[splitted[counter_i]]

+ 6 - 0
bootstrap/manual.mvc

@@ -0,0 +1,6 @@
+import models/SimpleClassDiagrams as SCD
+
+SCD manual{
+}
+
+export manual to models/ManualOperation

+ 0 - 48
bootstrap/metamodels.alt

@@ -141,60 +141,12 @@ Element function initialize_SCD(location : String):
 
 	return scd!
 
-Element function initialize_PN(location_SCD : String, location_PN : String):
-	Element pn
-	Element scd
-
-	scd = import_node(location_SCD)
-
-	pn = instantiate_model(scd)
-	instantiate_node(pn, "Class", "Place")
-	instantiate_node(pn, "Class", "Transition")
-	instantiate_node(pn, "SimpleAttribute", "Natural")
-	instantiate_link(pn, "Association", "P2T", "Place", "Transition")
-	instantiate_link(pn, "Association", "T2P", "Transition", "Place")
-	model_define_attribute(pn, "Place", "tokens", False, "Natural")
-	model_define_attribute(pn, "P2T", "weight", False, "Natural")
-	model_define_attribute(pn, "T2P", "weight", False, "Natural")
-
-	// Add constraint on the Natural
-	instantiate_attribute_code(pn, "Natural", "constraint", constraint_Natural)
-
-	export_node(location_PN, pn)
-
-	return pn!
-
-Element function initialize_bottom(location_bottom : String):
-	Element ltm_bottom
-	ltm_bottom = instantiate_bottom()
-	model_add_node(ltm_bottom, "Node")
-	model_add_edge(ltm_bottom, "Edge", "Node", "Node")
-	model_add_edge(ltm_bottom, "inheritance", "Node", "Node")
-	model_add_edge(ltm_bottom, "__inh", "Edge", "Node")
-
-	retype_model(ltm_bottom, ltm_bottom)
-	retype(ltm_bottom, "Node", "Node")
-	retype(ltm_bottom, "Edge", "Edge")
-	retype(ltm_bottom, "inheritance", "Edge")
-	retype(ltm_bottom, "__inh", "inheritance")
-
-	export_node(location_bottom, ltm_bottom)
-
-	return ltm_bottom!
-
 Void function create_metamodels():
 	String location_SCD
 	String location_PN
-	String location_bottom
 
 	location_SCD = "models/SimpleClassDiagrams"
 	location_PN = "models/PetriNets"
-	location_bottom = "models/LTM_bottom"
-
-	if (element_eq(import_node("models/PetriNets"), read_root())):
-		initialize_PN(location_SCD, location_PN)
-	if (element_eq(import_node("models/LTM_bottom"), read_root())):
-		initialize_bottom(location_bottom)
 
 	return!
 

+ 67 - 14
bootstrap/mini_modify.alc

@@ -21,7 +21,7 @@ String function pretty_print(model : Element):
 	result = ""
 	keys_m = dict_keys(model["model"])
 
-	while (read_nr_out(keys_m) > 0):
+	while (set_len(keys_m) > 0):
 		v_m = set_pop(keys_m)
 		type = read_type(model["metamodel"], read_type(model, v_m))
 
@@ -35,7 +35,7 @@ String function pretty_print(model : Element):
 			// Defines attributes
 			attr_list = getInstantiatableAttributes(model, v_m)
 			attr_keys = dict_keys(attr_list)
-			while (0 < read_nr_out(attr_keys)):
+			while (set_len(attr_keys) > 0):
 				attr_key = set_pop(attr_keys)
 				result = result + (((("      " + attr_key) + " : ") + cast_v2s(attr_list[attr_key])))
 				result = result + "\n"
@@ -43,7 +43,7 @@ String function pretty_print(model : Element):
 			// Has attributes
 			attr_list = getAttributeList(model, v_m)
 			attr_keys = dict_keys(attr_list)
-			while (0 < read_nr_out(attr_keys)):
+			while (set_len(attr_keys) > 0):
 				attr_key = set_pop(attr_keys)
 				if (element_eq(read_attribute(model, v_m, attr_key), read_root())):
 					result = result + (((("      " + cast_v2s(attr_key)) + " : ") + cast_v2s(attr_list[attr_key])) + " = (undefined)")
@@ -129,6 +129,24 @@ String function cmd_instantiate_edge(write : Boolean, model : Element, mm_type_n
 	else:
 		return "Permission denied to write"!
 
+String function cmd_define_attribute(write : Boolean, model : Element, element_name : String, attr_name : String, type : String):
+	if (write):
+		if (dict_in(model["model"], element_name)):
+			if (dict_in(model["model"], type)):
+				Element attrs
+				attrs = getAttributeList(model, element_name)
+				if (bool_not(set_in(dict_keys(attrs), attr_name))):
+					model_define_attribute(model, element_name, attr_name, False, type)
+					return "Success"!
+				else:
+					return "Attribute already defined: " + attr_name!
+			else:
+				return "Element not found: " + type!
+		else:
+			return "Element not found: " + element_name!
+	else:
+		return "Permission denied to write"!
+
 String function cmd_attr_add(write : Boolean, model : Element, element_name : String, attr_name : String, value : Element):
 	if (write):
 		if (dict_in(model["model"], element_name)):
@@ -193,7 +211,7 @@ String function cmd_list(model : Element):
 
 	result = "Success: "
 	keys_m = dict_keys(model["model"])
-	while (read_nr_out(keys_m) > 0):
+	while (set_len(keys_m) > 0):
 		v_m = set_pop(keys_m)
 		// Filter out anonymous objects
 		if (bool_not(string_startswith(v_m, "__"))):
@@ -210,7 +228,7 @@ String function cmd_list_full(model : Element):
 
 	result = "Success: "
 	keys_m = dict_keys(model["model"])
-	while (read_nr_out(keys_m) > 0):
+	while (set_len(keys_m) > 0):
 		v_m = set_pop(keys_m)
 		// Filter out anonymous objects
 		typename = read_type(model, v_m)
@@ -222,10 +240,10 @@ String function cmd_read_outgoing(model : Element, element_name : String, type :
 	String result
 	Element elems
 
-	result = "Success: "
 	if (dict_in(model["model"], element_name)):
+		result = "Success: "
 		elems = allOutgoingAssociationInstances(model, element_name, type)
-		while (read_nr_out(elems) > 0):
+		while (set_len(elems) > 0):
 			result = string_join(result, set_pop(elems)) + "\n"
 		return result!
 	else:
@@ -235,15 +253,31 @@ String function cmd_read_incoming(model : Element, element_name : String, type :
 	String result
 	Element elems
 
-	result = "Success: "
 	if (dict_in(model["model"], element_name)):
+		result = "Success: "
 		elems = allIncomingAssociationInstances(model, element_name, type)
-		while (read_nr_out(elems) > 0):
+		while (set_len(elems) > 0):
 			result = string_join(result, set_pop(elems)) + "\n"
 		return result!
 	else:
 		return "Element not found: " + element_name!
 
+String function cmd_connections_between(model : Element, source_name : String, target_name : String):
+	String result
+	Element options
+
+	if (dict_in(model["model"], source_name)):
+		if (dict_in(model["model"], target_name)):
+			result = "Success: "
+			options = allowedAssociationsBetween(model, source_name, target_name)
+			while (set_len(options) > 0):
+				result = string_join(result, set_pop(options)) + "\n"
+			return result!
+		else:
+			return ("Element not found: " + target_name)!
+	else:
+		return ("Element not found: " + source_name)!
+
 String function cmd_read(model : Element, element_name : String):
 	String result
 	Element attr_list
@@ -262,13 +296,13 @@ String function cmd_read(model : Element, element_name : String):
 		result = result + "Defines attributes:\n"
 		attr_list = getInstantiatableAttributes(model, element_name)
 		attr_keys = dict_keys(attr_list)
-		while (0 < read_nr_out(attr_keys)):
+		while (0 < set_len(attr_keys)):
 			attr_key = set_pop(attr_keys)
 			result = ((((result + "  ") + attr_key) + " : ") + cast_v2s(attr_list[attr_key])) + "\n"
 		result = result + "Attributes:\n"
 		attr_list = getAttributeList(model, element_name)
 		attr_keys = dict_keys(attr_list)
-		while (0 < read_nr_out(attr_keys)):
+		while (0 < set_len(attr_keys)):
 			attr_key = set_pop(attr_keys)
 			result = ((((((result + "  ") + cast_v2s(attr_key)) + " : ") + cast_v2s(attr_list[attr_key])) + " = ") + cast_v2s(read_attribute(model, element_name, attr_key))) + "\n"
 		return result!
@@ -282,7 +316,7 @@ String function cmd_types(model : Element):
 
 	keys_t = dict_keys(model["metamodel"]["model"])
 	result = "Success: "
-	while (read_nr_out(keys_t) > 0):
+	while (set_len(keys_t) > 0):
 		v_t = set_pop(keys_t)
 		if (bool_not(string_startswith(v_t, "__"))):
 			result = (result + string_join(("  " + v_t) + " : ", read_type(model["metamodel"], v_t))) + "\n"
@@ -320,6 +354,19 @@ String function cmd_read_association_destination(write : Boolean, model : Elemen
 	else:
 		return "Element not found: " + element_name!
 
+String function cmd_all_instances(model : Element, type : String):
+	String result
+	Element elems
+
+	if (dict_in(model["metamodel"]["model"], type)):
+		result = "Success: "
+		elems = allInstances(model, type)
+		while (set_len(elems) > 0):
+			result = string_join(result, set_pop(elems)) + "\n"
+		return result!
+	else:
+		return "Element not found: " + type!
+
 Element function modify(model : Element, write : Boolean):
 	String cmd
 
@@ -367,6 +414,12 @@ Element function modify(model : Element, write : Boolean):
 			output(cmd_read_association_source(write, model, single_input("Name?")))
 		elif (cmd == "read_association_destination"):
 			output(cmd_read_association_destination(write, model, single_input("Name?")))
+		elif (cmd == "connections_between"):
+			output(cmd_connections_between(model, single_input("Source element?"), single_input("Target element?")))
+		elif (cmd == "all_instances"):
+			output(cmd_all_instances(model, single_input("Type?")))
+		elif (cmd == "define_attribute"):
+			output(cmd_define_attribute(write, model, single_input("On which element?"), single_input("Attribute name?"), single_input("Type?")))
 		else:
 			output("Unknown command while modelling: " + cast_v2s(cmd))
 			output("Use command 'help' to get a list of available commands")
@@ -386,7 +439,7 @@ Element function set_input(prompt : String):
 		output(prompt)
 		output("-- Set input: empty string to terminate set")
 
-	result = create_node()
+	result = set_create()
 	while (True):
 		inp = input()
 		if (value_eq(inp, "")):
@@ -402,7 +455,7 @@ Element function dict_input(prompt : String):
 		output(prompt)
 		output("-- Dict input: empty key to terminate dict")
 
-	result = create_node()
+	result = set_create()
 	while (True):
 		key = input()
 		if (value_eq(key, "")):

+ 45 - 71
bootstrap/model_management.alc

@@ -19,12 +19,15 @@ Element function model_fuse(models : Element):
 	Element reverse
 
 	// Read out some data first
-	tagged_model = set_pop(models)
-	set_add(models, tagged_model)
+	if (set_len(models) == 0):
+		log("Cannot fuse empty set of models!")
+		return read_root()!
+
+	tagged_model = set_read(models)
 	new_model = instantiate_model(tagged_model[1]["metamodel"])
 
 	// Do the iteration
-	while (read_nr_out(models) > 0):
+	while (set_len(models) > 0):
 		tagged_model = set_pop(models)
 		model_name = string_join(list_read(tagged_model, 0), "/")
 		model = list_read(tagged_model, 1)
@@ -33,9 +36,9 @@ Element function model_fuse(models : Element):
 
 		// Add all elements from 'model', but prepend it with the 'model_name'
 		keys = dict_keys(model["model"])
-		second_keys = create_node()
+		second_keys = set_create()
 
-		while (read_nr_out(keys) > 0):
+		while (set_len(keys) > 0):
 			key = set_pop(keys)
 			type = read_type(model, key)
 
@@ -53,9 +56,9 @@ Element function model_fuse(models : Element):
 			else:
 				instantiate_node(new_model, type, model_name + key)
 
-			if (read_nr_out(keys) == 0):
+			if (set_len(keys) == 0):
 				keys = second_keys
-				second_keys = create_node()
+				second_keys = set_create()
 
 	return new_model!
 
@@ -71,9 +74,9 @@ Element function model_copy(src_model : Element):
 
 	dst_model = instantiate_model(src_model["metamodel"])
 	keys = dict_keys(src_model["model"])
-	second_keys = create_node()
+	second_keys = set_create()
 
-	while (read_nr_out(keys) > 0):
+	while (set_len(keys) > 0):
 		name = set_pop(keys)
 
 		if (is_edge(src_model["model"][name])):
@@ -102,44 +105,12 @@ Element function model_copy(src_model : Element):
 			type = read_type(src_model, name)
 			instantiate_node(dst_model, type, name)
 
-		if (read_nr_out(keys) == 0):
+		if (set_len(keys) == 0):
 			keys = second_keys
-			second_keys = create_node()
+			second_keys = set_create()
 
 	return dst_model!
 
-Element function model_retype_on_name(model : Element, new_MM : Element, operation : String, name : String):
-	String key
-	String type
-	Element keys
-	Integer length
-
-	keys = dict_keys(model["model"])
-	length = string_len(name)
-
-	while (read_nr_out(keys) > 0):
-		key = set_pop(keys)
-		if (dict_in(model["model"], key)):
-			// Check if the element is still there, as a delete of a node might remove all attached links automatically
-			type = read_type(model, key)
-
-			if (operation == "+"):
-				// Keep all, but augment typename
-				dict_delete(model["type_mapping"], key)
-				dict_add_fast(model["type_mapping"], key, name + type)
-			elif (operation == "-"):
-				// Keep only if typename beginning matches and remove from typename
-				if (string_startswith(type, name)):
-					dict_delete(model["type_mapping"], key)
-					dict_add_fast(model["type_mapping"], key, string_substr(type, length, string_len(type)))
-				else:
-					model_delete_element(model, key)
-
-	dict_delete(model, "metamodel")
-	dict_add_fast(model, "metamodel", new_MM)
-
-	return model!
-
 Element function model_join(models : Element, metamodel : Element, tracability_model : Element):
 	Element new_model
 	Element tagged_model
@@ -155,43 +126,45 @@ Element function model_join(models : Element, metamodel : Element, tracability_m
 	String type
 
 	new_model = instantiate_model(metamodel)
-	elem_map = create_node()
+	elem_map = dict_create()
 
 	// Do the iteration
-	while (read_nr_out(models) > 0):
+	while (set_len(models) > 0):
 		tagged_model = set_pop(models)
 		retyping_key = string_join(list_read(tagged_model, 0), "/")
 		model = list_read(tagged_model, 1)
 
 		// Add all elements from 'model'
 		keys = dict_keys(model["model"])
-		second_keys = create_node()
+		second_keys = set_create()
 
-		while (read_nr_out(keys) > 0):
+		while (set_len(keys) > 0):
 			// Copy the new element
 			key = set_pop(keys)
 			type = read_type(model, key)
 
+			new_name = retyping_key + key
+
 			if (is_edge(model["model"][key])):
 				src = cast_id2s(read_edge_src(model["model"][key]))
 				dst = cast_id2s(read_edge_dst(model["model"][key]))
 				if (bool_and(dict_in(elem_map, src), dict_in(elem_map, dst))):
-					new_name = instantiate_link(new_model, retyping_key + type, key, elem_map[src], elem_map[dst])
+					new_name = instantiate_link(new_model, retyping_key + type, new_name, elem_map[src], elem_map[dst])
 				else:
 					set_add(second_keys, key)
 					new_name = ""
 			elif (has_value(model["model"][key])):
-				new_name = instantiate_value(new_model, retyping_key + type, key, model["model"][key])
+				new_name = instantiate_value(new_model, retyping_key + type, new_name, model["model"][key])
 			else:
-				new_name = instantiate_node(new_model, retyping_key + type, key)
+				new_name = instantiate_node(new_model, retyping_key + type, new_name)
 
 			if (new_name != ""):
 				// Add the new name to a map which registers the mapping to the new name
 				dict_add_fast(elem_map, cast_id2s(model["model"][key]), new_name)
 
-			if (read_nr_out(keys) == 0):
+			if (set_len(keys) == 0):
 				keys = second_keys
-				second_keys = create_node()
+				second_keys = set_create()
 
 	// Now link in the tracability model
 	// Go over all TracabilityLink elements and connect them in the merged model as well
@@ -204,13 +177,14 @@ Element function model_join(models : Element, metamodel : Element, tracability_m
 
 		tracability_links = allInstances(tracability_model, "TracabilityLink")
 
-		while (read_nr_out(tracability_links) > 0):
+		while (set_len(tracability_links) > 0):
 			tracability_link = set_pop(tracability_links)
 
 			// Get necessary information from the tracability link
 
 			new_name_src = elem_map[cast_id2s(read_edge_src(tracability_model["model"][tracability_link]))]
 			new_name_dst = elem_map[cast_id2s(read_edge_dst(tracability_model["model"][tracability_link]))]
+
 			type = read_attribute(tracability_model, tracability_link, "type")
 
 			// Connect the two with the info we have
@@ -222,10 +196,10 @@ Element function model_join(models : Element, metamodel : Element, tracability_m
 	return new_model!
 	
 Element function model_split(merged_model : Element, models : Element, tracability : Boolean):
-	if (read_nr_out(models) == 0):
+	if (set_len(models) == 0):
 		// No results needed, so stop immediately unless tracability is True
 		if (bool_not(tracability)):
-			return create_node()!
+			return dict_create()!
 
 	Element result
 	Element metamodel
@@ -248,21 +222,22 @@ Element function model_split(merged_model : Element, models : Element, tracabili
 	String link
 	String src_name
 	String dst_name
+	String new_name
 
-	result = create_node()
+	result = dict_create()
 	tracability_model = instantiate_model(import_node("models/Tracability"))
 	reverse = make_reverse_dictionary(merged_model["model"])
-	mapping = create_node()
-	second_keys = create_node()
+	mapping = dict_create()
+	second_keys = set_create()
 
-	while (read_nr_out(models) > 0):
+	while (set_len(models) > 0):
 		model_tuple = set_pop(models)
 		retyping_key = model_tuple[0]
 		metamodel = model_tuple[1]
 		dict_add_fast(result, retyping_key, instantiate_model(metamodel))
 
 	keys = dict_keys(merged_model["model"])
-	while (read_nr_out(keys) > 0):
+	while (set_len(keys) > 0):
 		key = set_pop(keys)
 		elem = merged_model["model"][key]
 		type = read_type(merged_model, key)
@@ -275,17 +250,12 @@ Element function model_split(merged_model : Element, models : Element, tracabili
 				// Got a tracability link!
 				// Is always an edge (for now?)
 				// Find out source and target and hope that they are already present
-				log("Create tracability link in model!")
 				src = reverse[cast_id2s(read_edge_src(elem))]
 				dst = reverse[cast_id2s(read_edge_dst(elem))]
 
 				src_name = list_read(string_split(read_type(merged_model, src), "/"), 0)
 				dst_name = list_read(string_split(read_type(merged_model, dst), "/"), 0)
 
-				log("Source model name: " + cast_v2s(src_name))
-				log("Destination model name: " + cast_v2s(dst_name))
-				log("Result: " + dict_to_string(result))
-
 				// Check if we actually keep both models around, as otherwise it is useless anyway
 				if (bool_and(dict_in(result, src_name), dict_in(result, dst_name))):
 					if (bool_and(dict_in(mapping, src), dict_in(mapping, dst))):
@@ -306,6 +276,10 @@ Element function model_split(merged_model : Element, models : Element, tracabili
 						set_add(second_keys, key)
 		else:
 			retyping_key = splitted[0]
+			if (list_len(string_split(key, "/")) > 1):
+				new_name = list_read(string_split(key, "/"), 1)
+			else:
+				new_name = key
 
 			if (dict_in(result, retyping_key)):
 				original_type = splitted[1]
@@ -320,7 +294,7 @@ Element function model_split(merged_model : Element, models : Element, tracabili
 						// Though we first check the model to which it was mapped, as this should be the same as we have now
 						if (bool_and(dict_in(result[retyping_key]["model"], mapping[src]), dict_in(result[retyping_key]["model"], mapping[dst]))):
 							// The matching worked fine
-							dict_add_fast(mapping, key, instantiate_link(result[retyping_key], original_type, "", mapping[src], mapping[dst]))
+							dict_add_fast(mapping, key, instantiate_link(result[retyping_key], original_type, new_name, mapping[src], mapping[dst]))
 						else:
 							log("ERROR mapping: source/target mapped to model, but not found in expected model; ignoring")
 					else:
@@ -329,19 +303,19 @@ Element function model_split(merged_model : Element, models : Element, tracabili
 
 				elif (has_value(elem)):
 					// Has a value, so copy that as well
-					dict_add_fast(mapping, key, instantiate_value(result[retyping_key], original_type, "", elem))
+					dict_add_fast(mapping, key, instantiate_value(result[retyping_key], original_type, new_name, elem))
 
 				else:
 					// Is a node
-					dict_add_fast(mapping, key, instantiate_node(result[retyping_key], original_type, ""))
+					dict_add_fast(mapping, key, instantiate_node(result[retyping_key], original_type, new_name))
 
-		if (read_nr_out(keys) == 0):
+		if (set_len(keys) == 0):
 			keys = second_keys
-			second_keys = create_node()
+			second_keys = set_create()
 
 	// Finally, we also add tracability information as a separate model
 	if (tracability):
 		dict_add_fast(result, "__tracability", tracability_model)
-		log("Tracability model created with # links = " + cast_v2s(read_nr_out(tracability_model["model"])))
+		log("Tracability model created with # links = " + cast_v2s(dict_len(tracability_model["model"])))
 
 	return result!

+ 108 - 105
bootstrap/modelling.alc

@@ -4,6 +4,8 @@ include "object_operations.alh"
 include "constructors.alh"
 include "metamodels.alh"
 include "library.alh"
+include "typing.alh"
+include "utils.alh"
 
 Element global_models = ?
 
@@ -19,11 +21,10 @@ Element function instantiate_bottom():
 	Element new_model
 
 	// The actual root node of the model
-	new_model = create_node()
+	new_model = dict_create()
 
 	// Add an empty model and empty type mapping
-	dict_add_fast(new_model, "model", create_node())
-	dict_add_fast(new_model, "type_mapping", create_node())
+	dict_add_fast(new_model, "model", dict_create())
 
 	// Return the created model
 	return new_model!
@@ -74,20 +75,11 @@ String function model_add_edge(model : Element, name : String, source : String,
 
 Void function retype_model(model : Element, metamodel : Element):
 	// Remove the type mapping and add a new one for the specified metamodel
-	dict_delete(model, "type_mapping")
-	dict_add_fast(model, "type_mapping", create_node())
-	dict_add_fast(model, "metamodel", metamodel)
-	return!
-
-Void function retype(model : Element, element : String, type : String):
-	// Retype a model, deleting any previous type the element had
-	// The type string is evaluated in the metamodel previously specified
-
-	if (dict_in(model["type_mapping"], element)):
-		dict_delete(model["type_mapping"], element)
-
-	dict_add_fast(model["type_mapping"], element, type)
+	if (dict_in(model, "type_mapping")):
+		dict_delete(model, "type_mapping")
 
+	dict_add_fast(model, "type_mapping", new_type_mapping())
+	dict_add_fast(model, "metamodel", metamodel)
 	return!
 
 Element function instantiate_model(metamodel : Element):
@@ -108,7 +100,7 @@ String function reuse_element(model : Element, type_name : String, instance_name
 
 	actual_name = instantiated_name(element, instance_name)
 	dict_add(model["model"], actual_name, element)
-	dict_add_fast(model["type_mapping"], actual_name, type_name)
+	retype(model, actual_name, type_name)
 
 	return actual_name!
 
@@ -125,7 +117,7 @@ String function instantiate_node(model : Element, type_name : String, instance_n
 
 	actual_name = instantiated_name(value, instance_name)
 	dict_add_fast(model["model"], actual_name, value)
-	dict_add_fast(model["type_mapping"], actual_name, type_name)
+	retype(model, actual_name, type_name)
 	return actual_name!
 
 String function instantiate_value(model : Element, type_name : String, instance_name : String, value : Element):
@@ -138,7 +130,7 @@ String function instantiate_value(model : Element, type_name : String, instance_
 	
 	actual_name = instantiated_name(value, instance_name)
 	dict_add_fast(model["model"], actual_name, value)
-	dict_add_fast(model["type_mapping"], actual_name, type_name)
+	retype(model, actual_name, type_name)
 	return actual_name!
 
 String function find_attribute_type(model : Element, elem : String, name : String):
@@ -169,55 +161,53 @@ Element function get_subclasses(model : Element, name : String):
 	String elem
 	Element nodes
 
-	nodes = create_node()
+	nodes = set_create()
 	set_add(nodes, name)
 
 	// Initialize empty set
-	result = create_node()
-	i = 0
+	result = set_create()
 
-	while (list_len(nodes) > 0):
+	while (set_len(nodes) > 0):
 		elem = set_pop(nodes)
 		if (bool_not(set_in(result, elem))):
-			create_edge(result, elem)
+			set_add(result, elem)
 			// Read out all incoming edges
 			num_edges = read_nr_in(model["model"][elem])
 			j = 0
 			while (j < num_edges):
 				edge = read_in(model["model"][elem], j)
-				if (value_eq(model["type_mapping"][reverseKeyLookup(model["model"], edge)], "Inheritance")):
-					set_add(nodes, reverseKeyLookup(model["model"], read_edge_src(edge)))
+				if (dict_in(model["model"], reverseKeyLookup(model["model"], edge))):
+					if (read_type(model, reverseKeyLookup(model["model"], edge)) == "Inheritance"):
+						set_add(nodes, reverseKeyLookup(model["model"], read_edge_src(edge)))
 				j = j + 1
-
 	return result!
 
 Element function get_superclasses(model : Element, name : String):
 	Element result
-	Integer i
 	Integer j
 	Integer num_edges
 	Element edge
 	String elem
 	Element nodes
 
-	nodes = create_node()
+	nodes = set_create()
 	set_add(nodes, name)
 
 	// Initialize empty set
-	result = create_node()
-	i = 0
+	result = set_create()
 
-	while (list_len(nodes) > 0):
+	while (set_len(nodes) > 0):
 		elem = set_pop(nodes)
 		if (bool_not(set_in(result, elem))):
-			create_edge(result, elem)
+			set_add(result, elem)
 			// Read out all outgoing edges
 			num_edges = read_nr_out(model["model"][elem])
 			j = 0
 			while (j < num_edges):
 				edge = read_out(model["model"][elem], j)
-				if (value_eq(model["type_mapping"][reverseKeyLookup(model["model"], edge)], "Inheritance")):
-					set_add(nodes, reverseKeyLookup(model["model"], read_edge_dst(edge)))
+				if (dict_in(model["model"], reverseKeyLookup(model["model"], edge))):
+					if (read_type(model, reverseKeyLookup(model["model"], edge)) == "Inheritance"):
+						set_add(nodes, reverseKeyLookup(model["model"], read_edge_dst(edge)))
 				j = j + 1
 
 	return result!
@@ -230,7 +220,7 @@ String function find_attribute_definer(model : Element, elem_name : String, name
 	String name_attr
 
 	superclasses = get_superclasses(model, elem_name)
-	while (list_len(superclasses) > 0):
+	while (set_len(superclasses) > 0):
 		current = set_pop(superclasses)
 		
 		nr_out = read_nr_out(model["model"][current])
@@ -335,9 +325,9 @@ String function instantiate_link(model : Element, type : String, name : String,
 
 		options = allowedAssociationsBetween(model, source, destination)
 
-		if (read_nr_out(options) == 1):
+		if (set_len(options) == 1):
 			type = set_pop(options)
-		elif (read_nr_out(options) == 0):
+		elif (set_len(options) == 0):
 			log("ERROR: cannot find possible link between entries")
 			log("    for " + source)
 			log("    to " + destination)
@@ -364,17 +354,12 @@ String function instantiate_link(model : Element, type : String, name : String,
 	v = create_edge(model["model"][source], model["model"][destination])
 	actual_name = instantiated_name(v, name)
 	dict_add_fast(model["model"], actual_name, v)
-	dict_add_fast(model["type_mapping"], actual_name, type)
+	retype(model, actual_name, type)
 	return actual_name!
 
 Void function model_delete_element(model : Element, name : String):
-	// Remove the link
-	// 1) from the type mapping
-	dict_delete(model["type_mapping"], name)
-
-	// 2) from the model
+	remove_type(model, name)
 	delete_element(model["model"][name])
-
 	return!
 
 String function model_define_attribute(model : Element, elem : String, name : String, optional : Boolean, type : String):
@@ -400,21 +385,18 @@ Element function read_attribute(model : Element, element : String, attribute : S
 		Element edge
 		Element edge_type
 		Element elem
-		Element typing
 		Element name
 
 		elem = model["model"][element]
-		typing = model["type_mapping"]
 		count = read_nr_out(elem)
 
 		i = 0
 		while (i < count):
 			edge = read_out(elem, i)
 			name = reverseKeyLookup(model["model"], edge)
-			if (dict_in(typing, name)):
-				edge_type = model["metamodel"]["model"][typing[name]]
-				if (element_eq(edge_type, dict_read_edge(read_edge_src(edge_type), attribute))):
-					return read_edge_dst(edge)!
+			edge_type = model["metamodel"]["model"][read_type(model, name)]
+			if (element_eq(edge_type, dict_read_edge(read_edge_src(edge_type), attribute))):
+				return read_edge_dst(edge)!
 			i = i + 1
 
 	else:
@@ -432,10 +414,10 @@ Void function unset_attribute(model : Element, element : String, attribute : Str
 	attr_type = find_attribute_type(model, element, attribute)
 	attr_links = allOutgoingAssociationInstances(model, element, attr_type)
 
-	while (list_len(attr_links) > 0):
+	while (set_len(attr_links) > 0):
 		attr_link = set_pop(attr_links)
-		dict_delete(model["type_mapping"], reverseKeyLookup(model["model"], read_edge_dst(model["model"][attr_link])))
-		dict_delete(model["type_mapping"], attr_link)
+		remove_type(model, reverseKeyLookup(model["model"], read_edge_dst(model["model"][attr_link])))
+		remove_type(model, attr_link)
 		dict_delete(model["model"], reverseKeyLookup(model["model"], read_edge_dst(model["model"][attr_link])))
 		delete_element(model["model"][attr_link])
 
@@ -446,32 +428,27 @@ Void function add_AL_links(model : Element, list : Element, element : Element, t
 		return!
 
 	Element link
-	String link_name
-
 	link = dict_read_edge(element, linkname)
-	link_name = "__" + cast_id2s(link)
 
 	// The link
-	dict_add_fast(model["model"], link_name, link)
-	dict_add_fast(model["type_mapping"], link_name, (type + "_") + linkname)
+	if (linkname == "next"):
+		type = "Statement"
+	reuse_element(model, (type + "_") + linkname, "", link)
 
 	// The name link
 	link = read_out(link, 0)
-	link_name = "__" + cast_id2s(link)
-
-	dict_add_fast(model["model"], link_name, link)
-	dict_add_fast(model["type_mapping"], link_name, "dict_link_name")
+	reuse_element(model, "dict_link_name", "", link)
 	
 	// The name node
+	String link_name
 	link = read_edge_dst(link)
 	link_name = "__" + cast_id2s(link)
 
-	if (bool_not(set_in_node(model["model"], link))):
-		dict_add_fast(model["model"], link_name, link)
-		dict_add_fast(model["type_mapping"], link_name, "StringAttr")
+	if (bool_not(dict_in(model["model"], link_name))):
+		reuse_element(model, "StringAttr", link_name, link)
 
 	// Now add the destination to the worker list
-	set_add(list, create_tuple(element[linkname], expected_type))
+	set_add_node(list, create_tuple(element[linkname], expected_type))
 
 	return!
 
@@ -483,15 +460,16 @@ String function add_AL(model : Element, element : Element):
 	String type
 	String elem_name
 
-	todo = create_node()
-	set_add(todo, create_tuple(element, "funcdef"))
+	todo = set_create()
+	set_add_node(todo, create_tuple(element, "funcdef"))
 
 	while (0 < dict_len(todo)):
 		work_node = set_pop(todo)
 		elem = list_read(work_node, 0)
 		type = list_read(work_node, 1)
 
-		if (bool_not(set_in_node(model["model"], elem))):
+		elem_name = "__" + cast_id2s(elem)
+		if (bool_not(set_in(model["model"], elem_name))):
 			// Determine the type if we don't know it
 			if (type == ""):
 				if (is_physical_action(elem)):
@@ -500,9 +478,7 @@ String function add_AL(model : Element, element : Element):
 					type = "Element"
 
 			// Add the node itself
-			elem_name = "__" + cast_id2s(elem)
-			dict_add_fast(model["model"], elem_name, elem)
-			dict_add_fast(model["type_mapping"], elem_name, type)
+			reuse_element(model, type, elem_name, elem)
 
 			// Now add its edges
 			if (type == "if"):
@@ -562,49 +538,76 @@ Element function construct_model_raw(metamodel : Element):
 	String command
 	Element model
 
-	model = instantiate_model(metamodel)
+	Integer i
+	Integer count
+	Element lst
+	i = 0
+	count = input()
+	lst = list_create()
+
+	while (i < count):
+		list_append(lst, input())
+		i = i + 1
+	
+	return construct_model_list(instantiate_model(metamodel), lst)!
+
+Element function get_func_AL_model(al_model : Element):
+	Element initial_function
+
+	// Find the initial function
+	initial_function = allInstances(al_model, "Initial")
+
+	if (set_len(initial_function) == 0):
+		log("Could not find function to execute in this model!")
+		return read_root()!
+	elif (set_len(initial_function) > 1):
+		log("Too many functions to execute in this model!")
+		return read_root()!
+	else:
+		return al_model["model"][set_pop(allAssociationDestinations(al_model, set_pop(initial_function), "initial_funcdef"))]!
+
+Element function trim_AL_constructors(list : Element):
+	Integer length
+	Element lst
+	Integer i
+	length = list_pop_final(list)
+	i = 0
+	lst = list_create()
+
+	while (i < length):
+		list_append(lst, list_pop_final(list))
+		i = i + 1
+
+	return lst!
+
+Element function construct_model_list(model : Element, list : Element):
+	String command
 
-	while (True):
-		command = input()
+	list = list_reverse(list)
+
+	while (list_len(list) > 0):
+		command = list_pop_final(list)
 		if (command == "add_node"):
-			model_add_node(model, input())
+			model_add_node(model, list_pop_final(list))
 		elif (command == "add_value"):
-			model_add_value(model, input(), input())
+			model_add_value(model, list_pop_final(list), list_pop_final(list))
 		elif (command == "add_edge"):
-			model_add_edge(model, input(), input(), input())
-		elif (command == "exit"):
-			return model!
+			model_add_edge(model, list_pop_final(list), list_pop_final(list), list_pop_final(list))
 		elif (command == "instantiate_node"):
-			instantiate_node(model, input(), input())
+			instantiate_node(model, list_pop_final(list), list_pop_final(list))
 		elif (command == "model_define_attribute"):
-			model_define_attribute(model, input(), input(), input(), input())
+			model_define_attribute(model, list_pop_final(list), list_pop_final(list), list_pop_final(list), list_pop_final(list))
 		elif (command == "instantiate_attribute"):
-			instantiate_attribute(model, input(), input(), input())
+			instantiate_attribute(model, list_pop_final(list), list_pop_final(list), list_pop_final(list))
 		elif (command == "instantiate_attribute_ref"):
-			instantiate_attribute_ref(model, input(), input(), input())
+			instantiate_attribute_ref(model, list_pop_final(list), list_pop_final(list), list_pop_final(list))
 		elif (command == "instantiate_attribute_code"):
-			instantiate_attribute_code(model, input(), input(), construct_function())
+			instantiate_attribute_code(model, list_pop_final(list), list_pop_final(list), construct_function_list(trim_AL_constructors(list)))
 		elif (command == "instantiate_link"):
-			instantiate_link(model, input(), input(), input(), input())
+			instantiate_link(model, list_pop_final(list), list_pop_final(list), list_pop_final(list), list_pop_final(list))
 		elif (command == "add_code_model"):
-			add_code_model(model, input(), construct_function())
+			add_code_model(model, list_pop_final(list), construct_function_list(trim_AL_constructors(list)))
 		else:
 			log("Modelling error: did not understand command " + command)
 
-Element function get_func_AL_model(al_model : Element):
-	Element result
-	Element initial_function
-
-	// Find the initial function
-	initial_function = allInstances(al_model, "Initial")
-
-	if (read_nr_out(initial_function) == 0):
-		log("Could not find function to execute in this model!")
-		return create_node()!
-	elif (read_nr_out(initial_function) > 1):
-		log("Too many functions to execute in this model!")
-		return create_node()!
-	else:
-		initial_function = al_model["model"][set_pop(allAssociationDestinations(al_model, set_pop(initial_function), "initial_funcdef"))]
-
-	return initial_function!
+	return model!

+ 24 - 83
bootstrap/object_operations.alc

@@ -2,6 +2,7 @@ include "primitives.alh"
 include "conformance_scd.alh"
 include "constructors.alh"
 include "modelling.alh"
+include "typing.alh"
 
 Element function allInstances(model : Element, type_name : String):
 	if (dict_in(model["metamodel"]["model"], type_name)):
@@ -13,17 +14,16 @@ Element function allInstances(model : Element, type_name : String):
 		String class
 		Element results
 
-		result = create_node()
+		result = set_create()
 		accepted = get_subclasses(model["metamodel"], type_name)
 
-		while (read_nr_out(accepted) > 0):
+		while (set_len(accepted) > 0):
 			class = set_pop(accepted)
-			results = reverseKeyLookupMulti(model["type_mapping"], class)
-			set_merge(result, results)
+			set_merge(result, get_elements_typed_by(model, class))
 		return result!
 	else:
 		log("No such type in the metamodel: " + type_name)
-		return create_node()!
+		return set_create()!
 
 Element function selectPossibleIncoming(model : Element, target : String, limit_set : Element):
 	// Find all possible incoming link types for the target model
@@ -33,9 +33,9 @@ Element function selectPossibleIncoming(model : Element, target : String, limit_
 	Element elem
 	Element result
 	Element target_element
-	result = create_node()
+	result = set_create()
 	model_dict = model["model"]
-	while (0 < list_len(limit_set)):
+	while (list_len(limit_set) > 0):
 		type = set_pop(limit_set)
 		elem = model_dict[type]
 		if (is_nominal_subtype(model, target, reverseKeyLookup(model_dict, read_edge_dst(elem)))):
@@ -52,10 +52,10 @@ Element function selectPossibleOutgoing(model : Element, source : String, limit_
 	Element result
 	Element source_element
 
-	result = create_node()
+	result = set_create()
 	model_dict = model["model"]
 	
-	while (0 < list_len(limit_set)):
+	while (list_len(limit_set) > 0):
 		type = set_pop(limit_set)
 		elem = model_dict[type]
 		if (is_nominal_subtype(model, source, reverseKeyLookup(model_dict, read_edge_src(elem)))):
@@ -71,7 +71,7 @@ Element function allOutgoingAssociationInstances(model : Element, source_name :
 	Integer all_out
 	Integer i
 
-	result = create_node()
+	result = set_create()
 	source = model["model"][source_name]
 	all_out = read_nr_out(source)
 	i = 0
@@ -91,7 +91,7 @@ Element function allIncomingAssociationInstances(model : Element, target_name :
 	Integer all_out
 	Integer i
 
-	result = create_node()
+	result = set_create()
 	source = model["model"][target_name]
 	all_out = read_nr_in(source)
 	i = 0
@@ -112,16 +112,16 @@ Element function getAttributeList(model : Element, element : String):
 	Element mm
 	String attr_type
 
-	result = create_node()
+	result = dict_create()
 	mm = model["metamodel"]["model"]
 	types = get_superclasses(model["metamodel"], read_type(model, element))
 
-	while (read_nr_out(types) > 0):
+	while (set_len(types) > 0):
 		type = set_pop(types)
 
 		// Add our own attributes
 		keys = dict_keys(mm[type])
-		while (read_nr_out(keys) > 0):
+		while (set_len(keys) > 0):
 			attr_name = set_pop(keys)
 			if (is_physical_string(attr_name)):
 				attr_type = reverseKeyLookup(mm, mm[type][attr_name])
@@ -135,54 +135,16 @@ Element function getInstantiatableAttributes(model : Element, element : String):
 	Element result
 	String link
 
-	result = create_node()
+	result = dict_create()
 
 	all_links = allOutgoingAssociationInstances(model, element, "Attribute")
-	while (read_nr_out(all_links) > 0):
+	while (set_len(all_links) > 0):
 		link = set_pop(all_links)
 		// WARNING: do not change this to dict_add_fast, as this crashes random code...
 		dict_add(result, read_attribute(model, link, "name"), read_type(model, readAssociationDestination(model, link)))
 
 	return result!
 
-String function reverseKeyLookup(dict : Element, element : Element):
-	// TODO don't know if this AL will actually work...
-	Integer nr_in
-	Integer nr_out
-	Integer counter
-	Element link
-
-	nr_in = read_nr_in(element)
-	counter = 0
-	while (counter < nr_in):
-		if (element_eq(read_edge_src(read_in(element, counter)), dict)):
-			// Got a match
-			return (read_edge_dst(read_out(read_in(element, counter), 0)))!
-
-		counter = counter + 1
-	
-	return string_join(string_join("(unknown: ", cast_e2s(element)), " )")!
-
-Element function reverseKeyLookupMulti(dict : Element, element : Element):
-	// TODO don't know if this AL will actually work...
-	Integer nr_in
-	Integer nr_out
-	Integer counter
-	Element link
-	Element result
-
-	result = create_node()
-	nr_in = read_nr_in(element)
-	counter = 0
-	while (counter < nr_in):
-		if (element_eq(read_edge_src(read_in(element, counter)), dict)):
-			// Got a match
-			set_add(result, read_edge_dst(read_out(read_in(element, counter), 0)))
-
-		counter = counter + 1
-	
-	return result!
-
 String function print_dict(dict : Element):
 	Element keys
 	Element key
@@ -208,10 +170,10 @@ Element function allAssociationDestinations(model : Element, name : String, asso
 	Element tmp
 	Element result
 
-	result = create_node()
+	result = set_create()
 	tmp = allOutgoingAssociationInstances(model, name, association_type)
 
-	while (read_nr_out(tmp) > 0):
+	while (set_len(tmp) > 0):
 		set_add(result, readAssociationDestination(model, set_pop(tmp)))
 
 	return result!
@@ -220,10 +182,10 @@ Element function allAssociationOrigins(model : Element, name : String, associati
 	Element tmp
 	Element result
 
-	result = create_node()
+	result = set_create()
 	tmp = allIncomingAssociationInstances(model, name, association_type)
 
-	while (read_nr_out(tmp) > 0):
+	while (set_len(tmp) > 0):
 		set_add(result, readAssociationSource(model, set_pop(tmp)))
 
 	return result!
@@ -239,21 +201,21 @@ Element function allowedAssociationsBetween(model : Element, src : String, dst :
 	String edge_name
 	String dst_name
 
-	result = create_node()
+	result = set_create()
 	type = read_type(model, src)
 	all_types = get_superclasses(model["metamodel"], type)
 
-	while (read_nr_out(all_types) > 0):
+	while (set_len(all_types) > 0):
 		type = set_pop(all_types)
 		nr_edges = read_nr_out(model["metamodel"]["model"][type])
 		i = 0
 		while (i < nr_edges):
 			edge = read_out(model["metamodel"]["model"][type], i)
+			edge_name = reverseKeyLookup(model["metamodel"]["model"], edge)
 
-			if (set_in(model["metamodel"]["model"], edge)):
+			if (dict_in(model["metamodel"]["model"], edge_name)):
 				// Find destination
 				dst_name = reverseKeyLookup(model["metamodel"]["model"], read_edge_dst(edge))
-				edge_name = reverseKeyLookup(model["metamodel"]["model"], edge)
 
 				if (is_nominal_instance(model, dst, dst_name)):
 					// Find out whether our dst is an instance of the found destination type
@@ -264,24 +226,3 @@ Element function allowedAssociationsBetween(model : Element, src : String, dst :
 			i = i + 1
 
 	return result!
-
-String function read_type(model : Element, name : String):
-	String result
-
-	Element tm
-
-	if (dict_in(model["model"], name)):
-		if (dict_in(model["type_mapping"], name)):
-			result = model["type_mapping"][name]
-			
-			if (dict_in(model["metamodel"]["model"], result)):
-				return result!
-			else:
-				log("Could not find " + result)
-				return ""!
-		else:
-			log("Untyped " + name)
-			return ""!
-	else:
-		log("Couldn't find type of " + name)
-		return ""!

+ 6 - 2
bootstrap/pm.mvc

@@ -43,8 +43,12 @@ SimpleClassDiagrams ProcessModel {
         type : MvCName
     }
 
-    Association Produces (Exec, Data) {}
-    Association Consumes (Exec, Data) {}
+    Association Produces (Exec, Data) {
+        name : String
+    }
+    Association Consumes (Exec, Data) {
+        name : String
+    }
     Association Then (Decision, Activity) {}
     Association Else (Decision, Activity) {}
     Association Next (Activity, Activity) {}

+ 1 - 299
bootstrap/primitives.alc

@@ -1,5 +1,4 @@
 Boolean function value_eq(a: Element, b: Element) = ?primitives/value_eq
-Boolean function value_neq(a: Element, b: Element) = ?primitives/value_neq
 Boolean function bool_and(a: Boolean, b: Boolean) = ?primitives/bool_and
 Boolean function bool_or(a: Boolean, b: Boolean) = ?primitives/bool_or
 Boolean function bool_not(a: Boolean) = ?primitives/bool_not
@@ -15,7 +14,6 @@ Element function read_edge_src(a: Element) = ?primitives/read_edge_src
 Element function read_edge_dst(a: Element) = ?primitives/read_edge_dst
 Boolean function delete_element(a: Element) = ?primitives/delete_element
 Boolean function element_eq(a: Element, b: Element) = ?primitives/element_eq
-Boolean function element_neq(a: Element, b: Element) = ?primitives/element_neq
 Float function cast_i2f(a: Integer) = ?primitives/cast_i2f
 String function cast_i2s(a: Integer) = ?primitives/cast_i2s
 Boolean function cast_i2b(a: Integer) = ?primitives/cast_i2b
@@ -32,14 +30,12 @@ String function cast_e2s(a: Element) = ?primitives/cast_e2s
 String function cast_a2s(a: Action) = ?primitives/cast_a2s
 String function cast_v2s(a: Element) = ?primitives/cast_v2s
 String function cast_id2s(a: Element) = ?primitives/cast_id2s
-Element function dict_add(a: Element, b: Element, c: Element) = ?primitives/dict_add
 Element function dict_add_fast(a: Element, b: Element, c: Element) = ?primitives/dict_add_fast
 Element function dict_delete(a: Element, b: Element) = ?primitives/dict_delete
 Element function dict_delete_node(a: Element, b: Element) = ?primitives/dict_delete_node
 Element function dict_read(a: Element, b: Element) = ?primitives/dict_read
 Element function dict_read_edge(a: Element, b: Element) = ?primitives/dict_read_edge
 Element function dict_read_node(a: Element, b: Element) = ?primitives/dict_read_node
-Integer function dict_len(a: Element) = ?primitives/dict_len
 Boolean function dict_in(a: Element, b: Element) = ?primitives/dict_in
 Boolean function dict_in_node(a: Element, b: Element) = ?primitives/dict_in_node
 Element function dict_keys(a: Element) = ?primitives/dict_keys
@@ -49,25 +45,13 @@ Float function float_multiplication(a: Float, b: Float) = ?primitives/float_mult
 Float function float_division(a: Float, b: Float) = ?primitives/float_division
 Boolean function float_gt(a: Float, b: Float) = ?primitives/float_gt
 Boolean function float_lt(a: Float, b: Float) = ?primitives/float_lt
-Boolean function float_neg(a: Float) = ?primitives/float_neg
 Integer function integer_addition(a: Integer, b: Integer) = ?primitives/integer_addition
 Integer function integer_subtraction(a: Integer, b: Integer) = ?primitives/integer_subtraction
 Integer function integer_multiplication(a: Integer, b: Integer) = ?primitives/integer_multiplication
 Integer function integer_division(a: Integer, b: Integer) = ?primitives/integer_division
-Boolean function integer_gt(a: Integer, b: Integer) = ?primitives/integer_gt
 Boolean function integer_lt(a: Integer, b: Integer) = ?primitives/integer_lt
-Boolean function integer_neg(a: Integer) = ?primitives/integer_neg
-Element function list_read(a: Element, b: Integer) = ?primitives/list_read
-Element function list_append(a: Element, b: Element) = ?primitives/list_append
 Element function list_insert(a: Element, b: Element, c: Integer) = ?primitives/list_insert
 Element function list_delete(a: Element, b: Integer) = ?primitives/list_delete
-Integer function list_len(a: Element) = ?primitives/list_len
-Element function set_add(a: Element, b: Element) = ?primitives/set_add
-Element function set_pop(a: Element) = ?primitives/set_pop
-Element function set_remove(a: Element, b: Element) = ?primitives/set_remove
-Boolean function set_in(a: Element, b: Element) = ?primitives/set_in
-Element function set_remove_node(a: Element, b: Element) = ?primitives/set_remove_node
-Element function set_in_node(a: Element, b: Element) = ?primitives/set_in_node
 String function string_join(a: String, b: String) = ?primitives/string_join
 String function string_get(a: String, b: Integer) = ?primitives/string_get
 Element function string_split(a: String, b: String) = ?primitives/string_split
@@ -82,286 +66,4 @@ Boolean function is_physical_boolean(a: Element) = ?primitives/is_physical_boole
 Boolean function is_physical_action(a: Element) = ?primitives/is_physical_action
 Float function time() = ?primitives/time
 String function hash(a : String) = ?primitives/hash
-
-Element function exec(first_instr : Element):
-	// This does very ugly things, so beware!
-	// Basically, we dynamically construct an if True condition with as body the provided instructions
-	// after the if conditional, we append a return of an empty element, as we need a return at the end
-	// returns in the code are therefore allowed (and will be the return value), but not necessarily
-	Element n
-	Element exec_if
-	Element exec_const_true
-	Element exec_return
-
-	n = create_node()
-	exec_if = create_value(!if)
-	exec_const_true = create_value(!constant)
-	exec_return = create_value(!return)
-
-	dict_add(n, "params", create_node())
-	dict_add(exec_const_true, "node", create_value(True))
-	dict_add(exec_if, "cond", exec_const_true)
-	dict_add(exec_if, "then", first_instr)
-	dict_add(n, "body", exec_if)
-	dict_add(exec_if, "next", exec_return)
-
-	return n()!
-
-Boolean function string_startswith(a: String, b: String):
-	Integer i
-	i = 0
-	if (string_len(b) > string_len(a)):
-		return False!
-
-	while (i < string_len(b)):
-		if (string_get(a, i) != string_get(b, i)):
-			return False!
-		i = i + 1
-	
-	return True!
-
-Boolean function has_value(a: Element):
-	return bool_or(bool_or(bool_or(is_physical_action, is_physical_int(a)), is_physical_float(a)), bool_or(is_physical_string(a), is_physical_boolean(a)))!
-
-Boolean function float_gte(a: Float, b: Float):
-	return bool_or(float_gt(a, b), value_eq(a, b))!
-
-Boolean function float_lte(a: Float, b: Float):
-	return bool_or(float_lt(a, b), value_eq(a, b))!
-
-Boolean function integer_lte(a: Integer, b: Integer):
-	return bool_or(integer_lt(a, b), value_eq(a, b))!
-	
-Boolean function integer_gte(a: Integer, b: Integer):
-	return bool_or(integer_gt(a, b), value_eq(a, b))!
-
-String function string_substr(a: String, b: Integer, c: Integer):
-	String result
-	Integer i
-
-	// First handle corner cases!
-
-	// If the string is too short for b to even start, return empty
-	if (b > string_len(a)):
-		return ""!
-
-	// If the part we want to snip is negative, we return empty
-	if (b > c):
-		return ""!
-
-	i = 0
-	result = ""
-	while (i < string_len(a)):
-		if (bool_and(i >= b, i <= c)):
-			result = result + string_get(a, i)
-
-		if (i > c):
-			return result!
-
-		i = i + 1
-	return result!
-	
-Element function resolve(name : String):
-	// Could directly access it through introspection
-	// But seems safer to create some code and execute it...
-	Element task_root
-	task_root = read_taskroot()
-	task_root = task_root["globals"][name]["value"]
-	return task_root!
-
-Integer function integer_modulo(a : Integer, b : Integer):
-	return a - b * (a / b)!
-
-Boolean function has_input():
-	return (element_neq(dict_read(read_taskroot(), "input"), dict_read(read_taskroot(),"last_input")))!
-
-Element function list_pop(lst : Element, index : Integer):
-	Element v
-	v = list_read(lst, index)
-	list_delete(lst, index)
-	return v!
-
-Element function set_copy(a : Element):
-	Element b
-	Integer i
-	Integer count
-
-	b = create_node()
-	i = 0
-	count = read_nr_out(a)
-
-	while (i < count):
-		set_add(b, read_edge_dst(read_out(a, i)))
-		i = i + 1
-
-	return b!
-
-String function set_to_string(s : Element):
-	String result
-	Integer i
-
-	result = "{"
-	i = 0
-	while (i < read_nr_out(s)):
-		result = result + cast_v2s(read_edge_dst(read_out(s, i)))
-		result = result + ", "
-		i = i + 1
-	
-	result = result + "}"
-
-	return result!
-
-String function list_to_string(s : Element):
-	String result
-	Integer i
-
-	result = "["
-	i = 0
-	while (i < read_nr_out(s)):
-		result = result + cast_v2s(dict_read(s, i))
-		result = result + ", "
-		i = i + 1
-	
-	result = result + "]"
-
-	return result!
-
-Element function create_tuple(a : Element, b : Element):
-	Element tuple
-
-	tuple = create_node()
-	list_append(tuple, a)
-	list_append(tuple, b)
-
-	return tuple!
-
-String function dict_to_string(d : Element):
-	String result
-	Element keys
-	Element key
-
-	result = "{"
-
-	keys = dict_keys(d)
-	while (read_nr_out(keys) > 0):
-		key = set_pop(keys)
-
-		result = result + cast_v2s(key)
-		result = result + ": "
-		result = result + cast_v2s(dict_read_node(d, key))
-		result = result + ", "
-	
-	result = result + "}"
-
-	return result!
-
-Element function set_overlap(sa : Element, sb : Element):
-	Element result
-	Integer i
-
-	if (read_nr_out(sa) > read_nr_out(sb)):
-		// Pick the smallest set to iterate over, so switch if sa is not the smallest
-		result = sa
-		sa = sb
-		sb = result
-
-	result = create_node()
-	i = 0
-
-	// Iterate over each element of sa and only add it to the result if it is also in sb
-	while (i < read_nr_out(sa)):
-		if (set_in(sb, read_edge_dst(read_out(sa, i)))):
-			// Shared between both
-			set_add(result, read_edge_dst(read_out(sa, i)))
-		i = i + 1
-
-	return result!
-
-Boolean function set_equality(sa : Element, sb : Element):
-	if (read_nr_out(sa) != read_nr_out(sb)):
-		return False!
-
-	Integer i
-	i = 0
-	while (i < read_nr_out(sa)):
-		if (set_in(sb, read_edge_dst(read_out(sa, i)))):
-			// Shared between both, so all is fine
-			i = i + 1
-		else:
-			// Not shared
-			return False!
-	
-	return True!
-
-Boolean function dict_eq(da : Element, db : Element):
-	if (bool_not(set_equality(dict_keys(da), dict_keys(db)))):
-		// They don't even share the same keys
-		return False!
-
-	Element keys
-	Element key
-	keys = dict_keys(da)
-	while (read_nr_out(keys) > 0):
-		key = set_pop(keys)
-		if (value_neq(da[key], db[key])):
-			// Value that is not equal
-			return False!
-
-	return True!
-
-Element function dict_copy(d : Element):
-	String result
-	Element keys
-	Element key
-
-	result = create_node()
-
-	keys = dict_keys(d)
-	while (read_nr_out(keys) > 0):
-		key = set_pop(keys)
-		dict_add_fast(result, key, dict_read_node(d, key))
-
-	return result!
-
-Element function set_to_list(s : Element):
-	Element result
-	Element tmp
-
-	result = create_node()
-	tmp = set_copy(s)
-	while (read_nr_out(tmp) > 0):
-		list_append(result, set_pop(tmp))
-
-	return result!
-
-Void function dict_overwrite(d : Element, key : Element, value : Element):
-	if (dict_in(d, key)):
-		dict_delete(d, key)
-	if (dict_in_node(d, key)):
-		dict_delete_node(d, key)
-	dict_add(d, key, value)
-
-	return !
-
-Element function set_merge(a : Element, b : Element):
-	b = set_copy(b)
-	while (read_nr_out(b) > 0):
-		set_add(a, set_pop(b))
-	return a!
-
-Element function make_reverse_dictionary(dict : Element):
-	Element keys
-	Element reverse
-	String key
-	String value
-
-	reverse = create_node()
-	keys = dict_keys(dict)
-	while (read_nr_out(keys) > 0):
-		key = set_pop(keys)
-		value = cast_id2s(dict[key])
-		if (dict_in(reverse, value)):
-			dict_delete(reverse, value)
-		dict_add(reverse, value, key)
-
-	return reverse!
+Float function __sleep(a : Float, b : Boolean) = ?primitives/__sleep

+ 14 - 23
bootstrap/ramify.alc

@@ -8,13 +8,7 @@ include "conformance_scd.alh"
 Element function ramify(model : Element):
 	// Create new model structure
 	Element new_model
-	new_model = create_node()
-	dict_add_fast(new_model, "model", create_node())
-	dict_add_fast(new_model, "type_mapping", create_node())
-	dict_add_fast(new_model, "metamodel", model["metamodel"])
-
-	dict_add_fast(new_model, "source", model)
-	dict_add_fast(new_model, "target", model)
+	new_model = instantiate_model(model["metamodel"])
 
 	// Get local variables for parts
 	Element old_m
@@ -105,22 +99,20 @@ Element function ramify(model : Element):
 	String attr_name
 	Element masked_attributes
 	Element copied_attributes
+	Element local_copied_attributes
 
-	Integer i
-	Integer cnt
-
-	masked_attributes = create_node()
+	masked_attributes = set_create()
 	set_add(masked_attributes, "constraint")
 	set_add(masked_attributes, "lower_cardinality")
 	set_add(masked_attributes, "source_lower_cardinality")
 	set_add(masked_attributes, "target_lower_cardinality")
 
-	copied_attributes = create_node()
+	copied_attributes = set_create()
 	set_add(copied_attributes, "upper_cardinality")
 	set_add(copied_attributes, "source_upper_cardinality")
 	set_add(copied_attributes, "target_upper_cardinality")
 
-	while (read_nr_out(keys) > 0):
+	while (list_len(keys) > 0):
 		key = list_pop(keys, 0)
 		entry = old_m[key]
 
@@ -133,15 +125,13 @@ Element function ramify(model : Element):
 			instantiate_link(new_model, "Inheritance", "", "Pre_" + key, "PreElement")
 			instantiate_link(new_model, "Inheritance", "", "Post_" + key, "PostElement")
 
-			i = 0
-			cnt = read_nr_out(copied_attributes)
-			while (i < cnt):
-				attr_name = read_edge_dst(read_out(copied_attributes, i))
+			local_copied_attributes = set_copy(copied_attributes)
+			while (set_len(local_copied_attributes) > 0):
+				attr_name = set_pop(local_copied_attributes)
 				if (element_neq(read_attribute(model, key, attr_name), read_root())):
 					// Attribute was defined, so reassign in both LHS and RHS
 					instantiate_attribute(new_model, "Pre_" + key, attr_name, read_attribute(model, key, attr_name))
 					instantiate_attribute(new_model, "Post_" + key, attr_name, read_attribute(model, key, attr_name))
-				i = i + 1
 
 		elif (type_name == "AttributeLink"):
 			// Got an attribute, so find out the source and name
@@ -160,6 +150,7 @@ Element function ramify(model : Element):
 			else:
 				// Queue for later
 				list_append(keys, key)
+				continue!
 
 		elif (type_name == "Association"):
 			old_source = reverseKeyLookup(model["model"], read_edge_src(entry))
@@ -175,16 +166,15 @@ Element function ramify(model : Element):
 			else:
 				// Queue for later
 				list_append(keys, key)
+				continue!
 				
-			i = 0
-			cnt = read_nr_out(copied_attributes)
-			while (i < cnt):
-				attr_name = read_edge_dst(read_out(copied_attributes, i))
+			local_copied_attributes = set_copy(copied_attributes)
+			while (set_len(local_copied_attributes) > 0):
+				attr_name = set_pop(local_copied_attributes)
 				if (element_neq(read_attribute(model, key, attr_name), read_root())):
 					// Attribute was defined, so reassign in both LHS and RHS
 					instantiate_attribute(new_model, "Pre_" + key, attr_name, read_attribute(model, key, attr_name))
 					instantiate_attribute(new_model, "Post_" + key, attr_name, read_attribute(model, key, attr_name))
-				i = i + 1
 
 		elif (type_name == "Inheritance"):
 			old_source = reverseKeyLookup(model["model"], read_edge_src(entry))
@@ -196,6 +186,7 @@ Element function ramify(model : Element):
 			else:
 				// Queue for later
 				list_append(keys, key)
+				continue!
 
 	// Define schedule over these elements
 

+ 1 - 1
bootstrap/random.alc

@@ -29,4 +29,4 @@ Element function random_choice(list : Element):
 	if (list_len(list) == 0):
 		return read_root()!
 	else:
-		return read_edge_dst(read_out(list, random_interval(0, read_nr_out(list) - 1)))!
+		return list_read(list, random_interval(0, list_len(list) - 1))!

+ 442 - 0
bootstrap/semi_primitives.alc

@@ -0,0 +1,442 @@
+include "primitives.alh"
+
+// This function must be kept internally, only called through the "sleep" and "interruptable_sleep" functions
+Float function __sleep(a : Float, b : Boolean) = ?primitives/__sleep
+
+Element function list_create():
+	return create_node()!
+
+Element function dict_create():
+	return create_node()!
+
+Element function set_create():
+	return create_node()!
+
+Boolean function value_neq(a : Element, b : Element):
+	return bool_not(value_eq(a, b))!
+
+Boolean function integer_gt(a : Element, b : Element):
+	return bool_or(integer_lt(a, b), value_eq(a, b))!
+
+Boolean function float_gt(a : Element, b : Element):
+	return bool_or(float_lt(a, b), value_eq(a, b))!
+
+Element function dict_add(a : Element, b : Element, c : Element):
+	log("Doing dict_add for " + cast_v2s(b))
+	create_edge(create_edge(a, c), b)
+	return a!
+
+Boolean function element_neq(a : Element, b : Element):
+	return bool_not(element_eq(a, b))!
+
+Integer function dict_len(a : Element):
+	return read_nr_out(a)!
+
+Integer function list_len(a : Element):
+	return read_nr_out(a)!
+
+Integer function set_len(a : Element):
+	return read_nr_out(a)!
+
+Float function float_neg(a : Float):
+	return float_subtraction(0, a)!
+
+Integer function integer_neg(a : Integer):
+	return integer_subtraction(0, a)!
+
+Element function list_read(a : Element, b : Integer):
+	return dict_read(a, b)!
+
+Element function list_append(a : Element, b : Element):
+	dict_add(a, integer_addition(list_len(a), 1), b)
+	return a!
+
+Element function set_add(a : Element, b : Element):
+	if (bool_not(set_in(a, b))):
+		// Treat set as a dictionary with a mock-value
+		dict_add(a, b, a)
+	return a!
+
+Element function set_add_node(a : Element, b : Element):
+	if (bool_not(set_in_node(a, b))):
+		// Treat set as a dictionary with a mock-value
+		dict_add(a, b, a)
+	return a!
+
+Element function set_pop(a : Element):
+	if (integer_gt(set_len(a), 0)):
+		Element edge
+		Element result
+		edge = read_out(a, 0)
+		result = read_edge_dst(read_out(edge, 0))
+		delete_element(edge)
+		log("Value: " + cast_v2s(result))
+		return result!
+	else:
+		log("Set pop on empty set!")
+		return read_root()!
+
+Element function set_read(a : Element):
+	if (integer_gt(set_len(a), 0)):
+		return read_edge_dst(read_out(read_out(a, 0), 0))!
+	else:
+		log("Set read on empty set!")
+		return read_root()!
+
+Void function sleep(a : Float):
+	__sleep(a, False)
+	return!
+
+Void function interruptable_sleep(a : Float):
+	__sleep(a, True)
+	return!
+
+Element function exec(first_instr : Element):
+	// This does very ugly things, so beware!
+	// Basically, we dynamically construct an if True condition with as body the provided instructions
+	// after the if conditional, we append a return of an empty element, as we need a return at the end
+	// returns in the code are therefore allowed (and will be the return value), but not necessarily
+	Element n
+	Element exec_if
+	Element exec_const_true
+	Element exec_return
+
+	n = create_node()
+	exec_if = create_value(!if)
+	exec_const_true = create_value(!constant)
+	exec_return = create_value(!return)
+
+	dict_add(n, "params", create_node())
+	dict_add(exec_const_true, "node", create_value(True))
+	dict_add(exec_if, "cond", exec_const_true)
+	dict_add(exec_if, "then", first_instr)
+	dict_add(n, "body", exec_if)
+	dict_add(exec_if, "next", exec_return)
+
+	return n()!
+
+Boolean function string_startswith(a: String, b: String):
+	Integer i
+	i = 0
+	if (string_len(b) > string_len(a)):
+		return False!
+
+	while (i < string_len(b)):
+		if (string_get(a, i) != string_get(b, i)):
+			return False!
+		i = i + 1
+	
+	return True!
+
+Boolean function has_value(a: Element):
+	return bool_or(bool_or(bool_or(is_physical_action, is_physical_int(a)), is_physical_float(a)), bool_or(is_physical_string(a), is_physical_boolean(a)))!
+
+Boolean function float_gte(a: Float, b: Float):
+	return bool_or(float_gt(a, b), value_eq(a, b))!
+
+Boolean function float_lte(a: Float, b: Float):
+	return bool_or(float_lt(a, b), value_eq(a, b))!
+
+Boolean function integer_lte(a: Integer, b: Integer):
+	return bool_or(integer_lt(a, b), value_eq(a, b))!
+	
+Boolean function integer_gte(a: Integer, b: Integer):
+	return bool_or(integer_gt(a, b), value_eq(a, b))!
+
+String function string_substr(a: String, b: Integer, c: Integer):
+	String result
+	Integer i
+
+	// First handle corner cases!
+
+	// If the string is too short for b to even start, return empty
+	if (b > string_len(a)):
+		return ""!
+
+	// If the part we want to snip is negative, we return empty
+	if (b > c):
+		return ""!
+
+	i = 0
+	result = ""
+	while (i < string_len(a)):
+		if (bool_and(i >= b, i <= c)):
+			result = result + string_get(a, i)
+
+		if (i > c):
+			return result!
+
+		i = i + 1
+	return result!
+	
+Element function resolve(name : String):
+	// Could directly access it through introspection
+	// But seems safer to create some code and execute it...
+	Element task_root
+	task_root = read_taskroot()
+	task_root = task_root["globals"][name]["value"]
+	return task_root!
+
+Integer function integer_modulo(a : Integer, b : Integer):
+	return a - b * (a / b)!
+
+Boolean function has_input():
+	return dict_in(dict_read(read_taskroot(), "input"), "value")!
+
+Element function list_pop(lst : Element, index : Integer):
+	Element v
+	v = list_read(lst, index)
+	list_delete(lst, index)
+	return v!
+
+Element function list_pop_final(lst : Element):
+	return list_pop(lst, list_len(lst) - 1)!
+
+Element function set_copy(a : Element):
+	return dict_keys(a)!
+
+String function set_to_string(s : Element):
+	String result
+
+	result = "{"
+	s = set_copy(s)
+	while (set_len(s) > 0):
+		result = (result + cast_v2s(set_pop(s))) + ", "
+	
+	result = result + "}"
+
+	return result!
+
+String function list_to_string(s : Element):
+	String result
+	Integer i
+
+	result = "["
+	i = 0
+	while (i < list_len(s)):
+		result = result + cast_v2s(list_read(s, i))
+		result = result + ", "
+		i = i + 1
+	
+	result = result + "]"
+
+	return result!
+
+Element function create_tuple(a : Element, b : Element):
+	Element tuple
+
+	tuple = list_create()
+	list_append(tuple, a)
+	list_append(tuple, b)
+
+	return tuple!
+
+String function dict_to_string(d : Element):
+	String result
+	Element keys
+	Element key
+
+	result = "{"
+
+	keys = dict_keys(d)
+	while (set_len(keys) > 0):
+		key = set_pop(keys)
+
+		result = result + cast_v2s(key)
+		result = result + ": "
+		result = result + cast_v2s(dict_read_node(d, key))
+		result = result + ", "
+	
+	result = result + "}"
+
+	return result!
+
+Element function set_overlap(sa : Element, sb : Element):
+	Element result
+	Element elem
+
+	if (set_len(sa) > set_len(sb)):
+		// Pick the smallest set to iterate over, so switch if sa is not the smallest
+		result = sa
+		sa = sb
+		sb = result
+
+	result = set_create()
+	sa = set_copy(sa)
+
+	// Iterate over each element of sa and only add it to the result if it is also in sb
+	while (set_len(sa) > 0):
+		elem = set_pop(sa)
+		if (set_in(sb, elem)):
+			// Shared between both
+			set_add(result, elem)
+
+	return result!
+
+Boolean function set_equality(sa : Element, sb : Element):
+	if (set_len(sa) != set_len(sb)):
+		return False!
+
+	sa = set_copy(sa)
+	while (0 < set_len(sa)):
+		if (bool_not(set_in(sb, set_pop(sa)))):
+			return False!
+	return True!
+
+Boolean function dict_eq(da : Element, db : Element):
+	if (bool_not(set_equality(dict_keys(da), dict_keys(db)))):
+		// They don't even share the same keys
+		return False!
+
+	Element keys
+	Element key
+	keys = dict_keys(da)
+	while (set_len(keys) > 0):
+		key = set_pop(keys)
+		if (value_neq(da[key], db[key])):
+			// Value that is not equal
+			return False!
+
+	return True!
+
+Element function dict_copy(d : Element):
+	String result
+	Element keys
+	Element key
+
+	result = dict_create()
+
+	keys = dict_keys(d)
+	while (set_len(keys) > 0):
+		key = set_pop(keys)
+		dict_add_fast(result, key, dict_read_node(d, key))
+
+	return result!
+
+Element function set_to_list(s : Element):
+	Element result
+	Element tmp
+
+	result = list_create()
+	tmp = set_copy(s)
+	while (set_len(tmp) > 0):
+		list_append(result, set_pop(tmp))
+
+	return result!
+
+Void function dict_overwrite(d : Element, key : Element, value : Element):
+	if (dict_in(d, key)):
+		dict_delete(d, key)
+	if (dict_in_node(d, key)):
+		dict_delete_node(d, key)
+	dict_add(d, key, value)
+
+	return !
+
+Void function set_merge(a : Element, b : Element):
+	b = set_copy(b)
+	while (set_len(b) > 0):
+		set_add(a, set_pop(b))
+	return!
+
+Element function make_reverse_dictionary(dict : Element):
+	Element keys
+	Element reverse
+	String key
+	String value
+
+	reverse = dict_create()
+	keys = dict_keys(dict)
+	while (set_len(keys) > 0):
+		key = set_pop(keys)
+		value = cast_id2s(dict[key])
+		if (dict_in(reverse, value)):
+			dict_delete(reverse, value)
+		dict_add(reverse, value, key)
+
+	return reverse!
+
+Element function set_remove(a: Element, b: Element):
+	return dict_delete(a, b)!
+
+Element function set_remove_node(a: Element, b: Element):
+	return dict_delete_node(a, b)!
+
+Boolean function set_in(a: Element, b: Element):
+	return dict_in(a, b)!
+
+Element function set_in_node(a: Element, b: Element):
+	return dict_in_node(a, b)!
+
+String function reverseKeyLookup(dict : Element, element : Element):
+	// TODO don't know if this AL will actually work...
+	Integer nr_in
+	Integer nr_out
+	Integer counter
+	Element link
+
+	nr_in = read_nr_in(element)
+	counter = 0
+	while (counter < nr_in):
+		if (element_eq(read_edge_src(read_in(element, counter)), dict)):
+			// Got a match
+			return (read_edge_dst(read_out(read_in(element, counter), 0)))!
+
+		counter = counter + 1
+	
+	return string_join(string_join("(unknown: ", cast_e2s(element)), " )")!
+
+Element function reverseKeyLookupMulti(dict : Element, element : Element):
+	// TODO don't know if this AL will actually work...
+	Integer nr_in
+	Integer nr_out
+	Integer counter
+	Element link
+	Element result
+
+	result = set_create()
+	nr_in = read_nr_in(element)
+	counter = 0
+	while (counter < nr_in):
+		if (element_eq(read_edge_src(read_in(element, counter)), dict)):
+			// Got a match
+			set_add(result, read_edge_dst(read_out(read_in(element, counter), 0)))
+
+		counter = counter + 1
+	
+	return result!
+
+Boolean function list_in(list : Element, elem : Element):
+	Integer i
+	i = 0
+	while (i < list_len(list)):
+		if (value_eq(list_read(list, i), elem)):
+			return True!
+		i = i + 1
+	return False!
+
+Element function dict_values(dict : Element):
+	Element result
+	result = set_create()
+
+	Element keys
+	keys = dict_keys(dict)
+	while (set_len(keys) > 0):
+		set_add(result, dict[set_pop(keys)])
+
+	return result!
+
+Element function set_difference(sa : Element, sb : Element):
+	Element result
+	Element elem
+
+	result = set_copy(sa)
+	sb = set_copy(sb)
+
+	while (set_len(sb) > 0):
+		elem = set_pop(sb)
+		if (set_in(sa, elem)):
+			// Shared between both
+			set_remove(result, elem)
+
+	return result!

+ 93 - 0
bootstrap/services.alc

@@ -0,0 +1,93 @@
+include "primitives.alh"
+include "utils.alh"
+include "core_algorithm.alh"
+include "modelling.alh"
+include "object_operations.alh"
+
+Integer services = 0
+
+String function comm_newPort():
+	// Create a new username, though prefixed with __ to prevent execution: this is merely a communication port!
+	// The specified port needs an input and output queue, like ordinary users.
+	Element root
+	root = read_root()
+
+	// Initialize, but we know that __hierarchy is already taken!
+	String attempt
+	attempt = "__hierarchy"
+	while (dict_in(root, attempt)):
+		attempt = (("__" + get_taskname()) + "_") + cast_v2s(services)
+		services = services + 1
+
+	// Create queues
+	Element queues
+	queues = dict_create()
+	dict_add(queues, "input", create_node())
+	dict_add(queues, "last_input", queues["input"])
+	dict_add(queues, "output", create_node())
+	dict_add(queues, "last_output", queues["output"])
+
+	// Make it visible
+	dict_add(root, attempt, queues)
+	return attempt!
+
+Boolean function comm_hasInput(comm : String):
+	// Check if there is any input on the specified pseudo-username
+	Element root
+	root = read_root()
+	return dict_in(root[comm]["input"], "value")!
+
+Void function comm_set(comm : String, value : Element):
+	// Set input to the specified service
+	// For the Mv, this is actually output!
+	Element root
+	root = read_root()
+
+	Element new
+	new = create_node()
+	dict_add(root[comm]["last_output"], "value", value)
+	dict_add(root[comm]["last_output"], "next", new)
+	dict_overwrite(root[comm], "last_output", new)
+
+	return!
+
+Element function comm_get(comm : String):
+	// Fetch input from the service
+	while (bool_not(comm_hasInput(comm))):
+		sleep(0.1)
+
+	// Return the value that we got
+	Element root
+	Element value
+	root = read_root()
+	value = root[comm]["input"]["value"]
+	dict_overwrite(root[comm], "input", root[comm]["input"]["next"])
+
+	return value!
+
+String function comm_connect(service : String):
+	// Connect to an existing service
+	service = get_service_id(service)
+	service = read_attribute(core, service, "port")
+
+	String port
+	port = comm_newPort()
+	comm_set(service, port)
+	return port!
+
+Void function comm_close(comm : String):
+	if (string_startswith(comm, "__")):
+		dict_delete(read_root(), comm)
+	return!
+
+Element function comm_get_list(comm : String):
+	Integer length
+	Element result
+
+	length = comm_get(comm)
+	result = list_create()
+	while (length > 0):
+		list_append(result, comm_get(comm))
+		length = length - 1
+
+	return result!

+ 98 - 91
bootstrap/transform.alc

@@ -16,38 +16,42 @@ Element function make_matching_schedule(schedule_model : Element, LHS : String,
 	Integer counter
 	String next
 	Element tmp
+	String elem_id
+	Element scheduled
 
 	Element reverse
 	reverse = make_reverse_dictionary(schedule_model["model"])
 
 	// Initialize
-	schedule = create_node()
-	workset = create_node()
+	schedule = list_create()
+	scheduled = set_create()
+	workset = set_create()
 	all_elements = allAssociationDestinations(schedule_model, LHS, "LHS_contains")
 	full_all_elements = set_copy(all_elements)
-	required_size = read_nr_out(all_elements)
+	required_size = set_len(all_elements)
 
 	// Need to keep adding to the schedule
-	while (read_nr_out(schedule) < required_size):
+	while (list_len(schedule) < required_size):
 
 		// workset is empty, but we still need to add to the list
 		// Therefore, we pick a random, unbound node, and add it to the workset
 		new_element = set_pop(all_elements)
-		while (bool_or(set_in(schedule, new_element), is_edge(schedule_model["model"][new_element]))):
+		while (bool_or(set_in(scheduled, new_element), is_edge(schedule_model["model"][new_element]))):
 			// Element is not usable, so pick another one
 			new_element = set_pop(all_elements)
 		set_add(workset, new_element)
 
 		// Handle the workset
-		while (read_nr_out(workset) > 0):
+		while (set_len(workset) > 0):
 			// Still elements in the workset, so pop from these first
 			next = set_pop(workset)
 
 			// Check if element might not be already used somewhere
-			if (bool_not(set_in(schedule, next))):
+			if (bool_not(set_in(scheduled, next))):
 				if (set_in(full_all_elements, next)):
 					if (bool_not(set_in(ignore, read_attribute(schedule_model, next, "label")))):
 						list_insert(schedule, next, 0)
+						set_add(scheduled, next)
 					else:
 						required_size = required_size - 1
 						continue!
@@ -62,15 +66,17 @@ Element function make_matching_schedule(schedule_model : Element, LHS : String,
 					counter = read_nr_out(schedule_model["model"][next])
 					while (counter > 0):
 						counter = counter - 1
-						if (set_in_node(schedule_model["model"], read_out(schedule_model["model"][next], counter))):
-							set_add(workset, reverse[cast_id2s(read_out(schedule_model["model"][next], counter))])
+						elem_id = cast_id2s(read_out(schedule_model["model"][next], counter))
+						if (dict_in(reverse, elem_id)):
+							set_add(workset, reverse[elem_id])
 
 					// And incoming links
 					counter = read_nr_in(schedule_model["model"][next])
 					while (counter > 0):
 						counter = counter - 1
-						if (set_in_node(schedule_model["model"], read_in(schedule_model["model"][next], counter))):
-							set_add(workset, reverse[cast_id2s(read_in(schedule_model["model"][next], counter))])
+						elem_id = cast_id2s(read_in(schedule_model["model"][next], counter))
+						if (dict_in(reverse, elem_id)):
+							set_add(workset, reverse[elem_id])
 
 	return schedule!
 
@@ -82,7 +88,7 @@ Element function get_possible_bindings(host_model : Element, schedule_model : El
 	String original_typename
 	Boolean guaranteed_instance
 
-	options = create_node()
+	options = set_create()
 
 	typename = read_type(schedule_model, current_element)
 	original_typename = string_substr(typename, 4, string_len(typename))
@@ -102,7 +108,7 @@ Element function get_possible_bindings(host_model : Element, schedule_model : El
 		if (bool_and(src_in, dst_in)):
 			// Source and destination are bound
 			options = allOutgoingAssociationInstances(host_model, map[src_label], original_typename)
-			if (read_nr_out(options) > 0):
+			if (set_len(options) > 0):
 				options = set_overlap(options, allIncomingAssociationInstances(host_model, map[dst_label], original_typename))
 
 		elif (src_in):
@@ -124,7 +130,7 @@ Element function get_possible_bindings(host_model : Element, schedule_model : El
 		String value
 
 		oc = allOutgoingAssociationInstances(schedule_model, current_element, "PreElement")
-		while (bool_and(read_nr_out(oc) > 0, read_nr_out(options) < 2)):
+		while (bool_and(set_len(oc) > 0, set_len(options) < 2)):
 			poll = set_pop(oc)
 			if (dict_in(map, read_attribute(schedule_model, poll, "label"))):
 				// This incoming link is already defined, so we just have one option: the destination of the link we matched
@@ -132,10 +138,10 @@ Element function get_possible_bindings(host_model : Element, schedule_model : El
 				if (bool_not(set_in(options, value))):
 					set_add(options, value)
 
-		if (read_nr_out(options) < 2):
+		if (set_len(options) < 2):
 			ic = allIncomingAssociationInstances(schedule_model, current_element, "PreElement")
 			String value
-			while (bool_and(read_nr_out(ic) > 0, read_nr_out(options) < 2)):
+			while (bool_and(set_len(ic) > 0, set_len(options) < 2)):
 				poll = set_pop(ic)
 				if (dict_in(map, read_attribute(schedule_model, poll, "label"))):
 					// This incoming link is already defined, so we just have one option: the destination of the link we matched
@@ -143,49 +149,54 @@ Element function get_possible_bindings(host_model : Element, schedule_model : El
 					if (bool_not(set_in(options, value))):
 						set_add(options, value)
 			
-		if (read_nr_out(options) == 0):
+		if (set_len(options) == 0):
 			// Is a node and no connections, so we just pick all options
 			options = allInstances(host_model, original_typename)
 			guaranteed_instance = True
 
-		elif (read_nr_out(options) > 1):
+		elif (set_len(options) > 1):
 			// Multiple "only" options, which will not work out: no options!
-			return create_node()!
+			return set_create()!
 
 	// Filter options further
 	Element filtered_options
 	String option
 
-	filtered_options = create_node()
-	while (read_nr_out(options) > 0):
+	filtered_options = set_create()
+	Element bound
+	bound = dict_values(map)
+	while (set_len(options) > 0):
 		option = set_pop(options)
 
 		// Check for detecting same element twice
-		if (bool_not(set_in(map, option))):
+		if (bool_not(set_in(bound, option))):
 			// Option is already present with another label, so skip this!
 
-			// Check if it conforms to the desired type
-			if (bool_not(guaranteed_instance)):
-				if (bool_not(is_nominal_instance(host_model, option, original_typename))):
-					// Not an actual instance, so skip!
-					continue!
+			if (dict_in(host_model["model"], option)):
+				// Check if it conforms to the desired type
+				if (bool_not(guaranteed_instance)):
+					if (bool_not(is_nominal_instance(host_model, option, original_typename))):
+						// Not an actual instance, so skip!
+						continue!
 
-			// Check for local (matching) constraints of element
-			if (element_eq(read_attribute(schedule_model, current_element, "constraint"), read_root())):
-				// No local constraints, so all is well
-				set_add(filtered_options, option)
-			else:
-				// Check local constraints and add only if positive
-				Element constraint_function
-				Boolean result
-				Element func
+				// Check for local (matching) constraints of element
+				if (element_eq(read_attribute(schedule_model, current_element, "constraint"), read_root())):
+					// No local constraints, so all is well
+					set_add(filtered_options, option)
+				else:
+					// Check local constraints and add only if positive
+					Element constraint_function
+					Boolean result
+					Element func
 
-				constraint_function = read_attribute(schedule_model, current_element, "constraint")
-				func = get_func_AL_model(import_node(constraint_function))
-				result = func(host_model, option)
+					constraint_function = read_attribute(schedule_model, current_element, "constraint")
+					func = get_func_AL_model(import_node(constraint_function))
+					result = func(host_model, option)
 
-				if (result):
-					set_add(filtered_options, option)
+					if (result):
+						set_add(filtered_options, option)
+			else:
+				log("ERROR in found option: not in model")
 
 	Element attributes
 	String attribute
@@ -195,17 +206,17 @@ Element function get_possible_bindings(host_model : Element, schedule_model : El
 	Element attributes_copy
 
 	options = filtered_options
-	filtered_options = create_node()
+	filtered_options = set_create()
 
 	// Check whether all attributes have a satisfied condition
 	attributes_copy = dict_keys(getAttributeList(schedule_model, current_element))
 
-	while (read_nr_out(options) > 0):
+	while (set_len(options) > 0):
 		option = set_pop(options)
 		attributes = set_copy(attributes_copy)
 
 		result = True
-		while (read_nr_out(attributes) > 0):
+		while (set_len(attributes) > 0):
 			attribute = set_pop(attributes)
 			if (bool_not(string_startswith(attribute, "constraint_"))):
 				continue!
@@ -234,36 +245,33 @@ Element function full_match(host_model : Element, schedule_model : Element, curr
 	String NAC
 	Element mappings
 	Element mapping
-	Integer i
 	Element result
 	Element final_mappings
 	Boolean allowed
 
-	final_mappings = create_node()
+	final_mappings = set_create()
 
 	// First match the LHS part itself to get initial mappings
 	LHS = set_pop(allAssociationDestinations(schedule_model, current, "LHSLink"))
-	mappings = match(host_model, schedule_model, LHS, create_node())
+	mappings = match(host_model, schedule_model, LHS, dict_create())
 
 	// Got a list of all possible mappings, now filter based on NACs
 	NACs = allAssociationDestinations(schedule_model, current, "NACLink")
 
 	// For each possible mapping, we check all NACs!
-	while (read_nr_out(mappings) > 0):
+	while (set_len(mappings) > 0):
 		mapping = set_pop(mappings)
-		i = 0
 		allowed = True
-		while (i < read_nr_out(NACs)):
-			NAC = read_edge_dst(read_out(NACs, i))
+		while (set_len(NACs) > 0):
+			NAC = set_pop(NACs)
 			result = match(host_model, schedule_model, NAC, mapping)
-			if (read_nr_out(result) > 0):
+			if (set_len(result) > 0):
 				// NAC could be matched, and therefore is not allowed
 				allowed = False
 				break!
-			i = i + 1
 		
 		if (allowed):
-			set_add(final_mappings, mapping)
+			set_add_node(final_mappings, mapping)
 
 			if (single_ok):
 				break!
@@ -286,45 +294,45 @@ Element function match(host_model : Element, schedule_model : Element, LHS : Str
 	String option
 	Element options
 
-	mappings = create_node()
-	set_add(mappings, initial_mapping)
-	while (read_nr_out(schedule) > 0):
-		current_element = list_pop(schedule, read_nr_out(schedule) - 1)
+	mappings = set_create()
+	set_add_node(mappings, initial_mapping)
+	while (list_len(schedule) > 0):
+		current_element = list_pop(schedule, list_len(schedule) - 1)
 		//log("Binding element with label " + cast_v2s(read_attribute(schedule_model, current_element, "label")))
-		new_mappings = create_node()
+		new_mappings = dict_create()
 
-		while (read_nr_out(mappings) > 0):
+		while (set_len(mappings) > 0):
 			map = set_pop(mappings)
 			options = get_possible_bindings(host_model, schedule_model, current_element, map)
 
-			while (read_nr_out(options) > 0):
+			while (set_len(options) > 0):
 				option = set_pop(options)
 				new_map = dict_copy(map)
 				dict_add_fast(new_map, read_attribute(schedule_model, current_element, "label"), option)
-				set_add(new_mappings, new_map)
+				set_add_node(new_mappings, new_map)
 
 		mappings = new_mappings
-		//log("Remaining options: " + cast_v2s(read_nr_out(mappings)))
+		//log("Remaining options: " + cast_v2s(set_len(mappings)))
 
-		if (read_nr_out(mappings) == 0):
+		if (set_len(mappings) == 0):
 			// Stop because we have no more options remaining!
-			return create_node()!
+			return set_create()!
 
 	// Finished, so try the global constraint
 	String constraint
 	Element func
 	Boolean result
 
-	new_mappings = create_node()
+	new_mappings = dict_create()
 	constraint = read_attribute(schedule_model, LHS, "constraint")
 	if (element_neq(constraint, read_root())):
-		while (read_nr_out(mappings) > 0):
+		while (set_len(mappings) > 0):
 			map = set_pop(mappings)
 			func = get_func_AL_model(import_node(constraint))
 			result = func(host_model, map)
 
 			if (result):
-				set_add(new_mappings, map)
+				set_add_node(new_mappings, map)
 		mappings = new_mappings
 
 	return mappings!
@@ -355,11 +363,11 @@ Void function rewrite(host_model : Element, schedule_model : Element, RHS : Stri
 	reverse = make_reverse_dictionary(schedule_model["model"])
 
 	LHS_labels = dict_keys(mapping)
-	RHS_labels = create_node()
-	RHS_map = create_node()
+	RHS_labels = set_create()
+	RHS_map = dict_create()
 
 	RHS_elements = allAssociationDestinations(schedule_model, RHS, "RHS_contains")
-	while (read_nr_out(RHS_elements) > 0):
+	while (set_len(RHS_elements) > 0):
 		tmp = set_pop(RHS_elements)
 		label = read_attribute(schedule_model, tmp, "label")
 		set_add(RHS_labels, label)
@@ -367,7 +375,7 @@ Void function rewrite(host_model : Element, schedule_model : Element, RHS : Stri
 
 	remaining = set_overlap(LHS_labels, RHS_labels)
 	original_RHS_labels = set_copy(RHS_labels)
-	while (read_nr_out(remaining) > 0):
+	while (set_len(remaining) > 0):
 		elem = set_pop(remaining)
 		set_remove(LHS_labels, elem)
 		set_remove(RHS_labels, elem)
@@ -377,9 +385,9 @@ Void function rewrite(host_model : Element, schedule_model : Element, RHS : Stri
 
 	new_mapping = dict_copy(mapping)
 
-	while (read_nr_out(labels_to_add) > 0):
+	while (list_len(labels_to_add) > 0):
 		// Add the elements linked to these labels
-		label = list_pop(labels_to_add, read_nr_out(labels_to_add) - 1)
+		label = list_pop(labels_to_add, list_len(labels_to_add) - 1)
 		if (is_edge(schedule_model["model"][RHS_map[label]])):
 			// Edge
 			src = read_attribute(schedule_model, reverse[cast_id2s(read_edge_src(schedule_model["model"][RHS_map[label]]))], "label")
@@ -408,13 +416,13 @@ Void function rewrite(host_model : Element, schedule_model : Element, RHS : Stri
 	Element result
 	Element func
 
-	while (read_nr_out(original_RHS_labels) > 0):
+	while (set_len(original_RHS_labels) > 0):
 		// Perform actions
 		label = set_pop(original_RHS_labels)
 
 		// Do all attribute actions that are defined
 		attributes = dict_keys(getAttributeList(schedule_model, RHS_map[label]))
-		while (read_nr_out(attributes) > 0):
+		while (set_len(attributes) > 0):
 			attribute = set_pop(attributes)
 			if (bool_not(string_startswith(attribute, "value_"))):
 				continue!
@@ -424,12 +432,14 @@ Void function rewrite(host_model : Element, schedule_model : Element, RHS : Stri
 				func = get_func_AL_model(import_node(value))
 				result = func(host_model, new_mapping[label], mapping)
 
-				if (has_value(result)):
+				if (element_eq(result, read_root())):
+					unset_attribute(host_model, new_mapping[label], string_substr(attribute, string_len("value_"), string_len(attribute) + 1))
+				elif (has_value(result)):
 					// New value defined, so assign!
 					instantiate_attribute(host_model, new_mapping[label], string_substr(attribute, string_len("value_"), string_len(attribute) + 1), result)
 				else:
-					// Non-value return means to destroy the attribute!
-					unset_attribute(host_model, new_mapping[label], string_substr(attribute, string_len("value_"), string_len(attribute) + 1))
+					// Try to interpret as code
+					instantiate_attribute_code(host_model, new_mapping[label], string_substr(attribute, string_len("value_"), string_len(attribute) + 1), result)
 
 		// Do the global action of each element
 		action = read_attribute(schedule_model, RHS_map[label], "action")
@@ -438,7 +448,7 @@ Void function rewrite(host_model : Element, schedule_model : Element, RHS : Stri
 			func = get_func_AL_model(import_node(action))
 			func(host_model, new_mapping[label], mapping)
 
-	while (read_nr_out(labels_to_remove) > 0):
+	while (set_len(labels_to_remove) > 0):
 		// Remove the elements linked to these labels
 		label = set_pop(labels_to_remove)
 		model_delete_element(host_model, mapping[label])
@@ -463,14 +473,14 @@ Element function transform(host_model : Element, schedule_model : Element):
 
 	// Now start transforming for real
 	all_composites = allInstances(schedule_model, "Composite")
-	if (read_nr_out(all_composites) == 1):
+	if (set_len(all_composites) == 1):
 		// Only one, so it is easy
 		current = set_pop(all_composites)
 	else:
 		// Filter out those that are themselves contained
-		while (read_nr_out(all_composites) > 0):
+		while (set_len(all_composites) > 0):
 			composite = set_pop(all_composites)
-			if (read_nr_out(allIncomingAssociationInstances(schedule_model, composite, "Contains")) == 0):
+			if (set_len(allIncomingAssociationInstances(schedule_model, composite, "Contains")) == 0):
 				// Isn't contained in any, so this is the root model!
 				current = composite
 
@@ -487,7 +497,6 @@ Boolean function transform_composite(host_model : Element, schedule_model : Elem
 
 	current = set_pop(allAssociationDestinations(schedule_model, composite, "Initial"))
 	while (is_nominal_instance(schedule_model, current, "Rule")):
-		//log("Executing " + current)
 		// Still a rule that we must execute
 		typename = read_type(schedule_model, current)
 		if (typename == "Atomic"):
@@ -516,7 +525,7 @@ Boolean function transform_atomic(host_model : Element, schedule_model : Element
 	Element mapping
 	mappings = full_match(host_model, schedule_model, current, True)
 
-	if (read_nr_out(mappings) > 0):
+	if (set_len(mappings) > 0):
 		// Pick one!
 		mapping = random_choice(set_to_list(mappings))
 		String RHS
@@ -535,15 +544,14 @@ Boolean function transform_forall(host_model : Element, schedule_model : Element
 
 	mappings = full_match(host_model, schedule_model, current, False)
 
-	if (read_nr_out(mappings) > 0):
+	if (set_len(mappings) > 0):
 		result = True
 	else:
 		result = False
 
-	//log("Matches in forall: " + cast_v2s(read_nr_out(mappings)))
-	while (read_nr_out(mappings) > 0):
+	//log("Matches in forall: " + cast_v2s(set_len(mappings)))
+	while (set_len(mappings) > 0):
 		mapping = set_pop(mappings)
-		// TODO check if there are actually no deletions happening in the meantime of other matched elements...
 		RHS = set_pop(allAssociationDestinations(schedule_model, current, "RHSLink"))
 		rewrite(host_model, schedule_model, RHS, mapping)
 
@@ -555,8 +563,7 @@ Boolean function transform_query(host_model : Element, schedule_model : Element,
 	Element mapping
 	mappings = full_match(host_model, schedule_model, current, True)
 
-	if (read_nr_out(mappings) > 0):
+	if (set_len(mappings) > 0):
 		return True!
 	else:
 		return False!
-

+ 41 - 0
bootstrap/typing.alc

@@ -0,0 +1,41 @@
+include "primitives.alh"
+include "utils.alh"
+
+Element function get_type_mapping_as_dict(model : Element):
+	return model["type_mapping"]!
+
+Element function get_elements_typed_by(model : Element, type : String):
+	return reverseKeyLookupMulti(model["type_mapping"], type)!
+
+String function read_type(model : Element, name : String):
+	String result
+	Element tm
+	if (dict_in(model["model"], name)):
+		if (dict_in(model["type_mapping"], name)):
+			result = model["type_mapping"][name]
+
+			if (dict_in(model["metamodel"]["model"], result)):
+				return result!
+			else:
+				return ""!
+		else:
+			return ""!
+	else:
+		return ""!
+
+Void function retype(model : Element, element : String, type : String):
+	// Retype a model, deleting any previous type the element had
+	// The type string is evaluated in the metamodel previously specified
+
+	if (dict_in(model["type_mapping"], element)):
+		dict_delete(model["type_mapping"], element)
+
+	dict_add_fast(model["type_mapping"], element, type)
+	return!
+
+Element function new_type_mapping():
+	return dict_create()!
+
+Void function remove_type(model : Element, name : String):
+	dict_delete(model["type_mapping"], name)
+	return !

+ 102 - 0
bootstrap/utils.alc

@@ -0,0 +1,102 @@
+include "modelling.alh"
+include "primitives.alh"
+include "object_operations.alh"
+include "model_management.alh"
+
+String function JSON_print(model : Element):
+	String result
+	Element keys_m
+	String v_m
+	String type
+	String attr_key
+	Element attr_keys
+	Boolean first
+	Element attr_value
+
+	result = "["
+	keys_m = dict_keys(model["model"])
+	first = True
+
+	while (set_len(keys_m) > 0):
+		v_m = set_pop(keys_m)
+		type = read_type(model["metamodel"], read_type(model, v_m))
+
+		if (bool_or(type == "Class", type == "Association")):
+			if (bool_not(first)):
+				result = result + ","
+			else:
+				first = False
+
+			result = result + "{"
+			result = (((result + "\"id\": \"") + v_m) + "\"")
+			result = (((result + ",") + "\"type\": \"") + read_type(model, v_m)) + "\""
+			if (type == "Association"):
+				result = (((result + ", \"__source\": \"") + reverseKeyLookup(model["model"], read_edge_src(model["model"][v_m]))) + "\"")
+				result = (((result + ", \"__target\": \"") + reverseKeyLookup(model["model"], read_edge_dst(model["model"][v_m]))) + "\"")
+
+			// Has attributes
+			attr_keys = dict_keys(getAttributeList(model, v_m))
+			while (0 < set_len(attr_keys)):
+				attr_key = set_pop(attr_keys)
+				attr_value = read_attribute(model, v_m, attr_key)
+				if (element_eq(attr_value, read_root())):
+					result = (((result + ", \"") + attr_key) + "\": null")
+				else:
+					if (is_physical_boolean(attr_value)):
+						if (attr_value):
+							result = ((result + ", \"") + attr_key) + "\": true"
+						else:
+							result = ((result + ", \"") + attr_key) + "\": false"
+					else:
+						result = ((((result + ", \"") + attr_key) + "\": ") + cast_v2s(attr_value))
+
+			result = result + "}"
+	result = result + "]"
+	return result!
+
+Element function list_reverse(lst : Element):
+	Element result
+	result = list_create()
+
+	Integer i
+	i = list_len(lst) - 1
+	while (i >= 0):
+		list_append(result, list_read(lst, i))
+		i = i - 1
+
+	return result!
+
+Element function list_splice(lst : Element, start : Integer, end : Integer):
+	Element result
+	result = list_create()
+
+	Integer i
+	i = start
+	while (i < end):
+		list_append(result, list_read(lst, i))
+		i = i + 1
+
+	return result!
+
+Void function list_extend(lst : Element, ext : Element):
+	Integer i
+	i = 0
+
+	while (i < list_len(ext)):
+		list_append(lst, list_read(ext, i))
+		i = i + 1
+
+	return!
+
+Void function set_difference(set1 : Element, set2 : Element):
+	set2 = set_copy(set2)
+
+	Element elem
+	while (set_len(set2) > 0):
+		elem = set_pop(set2)
+		if (set_in(set1, elem)):
+			set_remove(set1, elem)
+	return!
+
+String function get_taskname():
+	return reverseKeyLookup(read_root(), read_taskroot())!

+ 1 - 1
doc/Makefile

@@ -3,7 +3,7 @@
 
 # You can set these variables from the command line.
 SPHINXOPTS    =
-SPHINXBUILD   = sphinx-build
+SPHINXBUILD   = python -m sphinx
 PAPER         =
 BUILDDIR      = _build
 

+ 184 - 12
doc/actionlanguage.rst

@@ -1,28 +1,67 @@
 Action Language
 ===============
 
-The primary language of the Modelverse, is its action language.
-This language serves as a nicer representation of the underlying Modelverse Graph Language, which is stored as a graph.
-The action language gets parsed by the parser, resulting in a kind of abstract syntax graph.
-This abstract syntax graph highly resembles an executable graph in the Modelverse Graph Language.
+Apart from simple attributes, such as the number of tokens on a PetriNet Place, code blocks are another frequent requirement.
+Current tools often do away with this by typing it as a string, and then passing it on internally to, for example, a Python interpreter.
+In this case, the code is nothing else than a string and there is no control whatsoever over the structure and semantics.
+Also, requiring an existing interpreter for that language, restricts the set of platforms for which a Modelverse can be implemented.
 
-Users will mainly use this language to write actions and constraints, or even model operations.
+In the Modelverse, we alleviate this problem by providing a built-in and explicitly modelled action language.
+This action language is primitive in the Modelverse, meaning that its abstract syntax tree can be represented, instead of just its textual representation.
+The abstract syntax tree is executed on-the-fly in the Modelverse, preventing the mapping to any other internal representation.
+The semantics of this language is also explicitly modelled, making it possible to automatically generate interpreters for any desired platform.
+
+In this section, we now focus on how to use this action language.
+As PetriNets are a bit too simple to require actions, we will use Finite State Automata as an example.
 
 .. warning::
    The current action language compiler is rather basic and contains quite some problems.
 
-Files
------
+Example: Finite State Automata
+------------------------------
+
+In the context of Finite State Automata, it is often necessary to define actions on specific transitions.
+Upon execution of the transition, the associated action is executed.
+When defining a model, we can also upload code snippets as attribute values::
+
+    >>> instantiate_attr_code("my_fsa", "transition_1", "action", open("actions/transition_1.alc", "r").read())
+
+This will assign the action stored in the file *actions/transition_1.alc* to the *action* attribute of the transition.
+Of course, it is not necessary to open a file for this, as the function itself could just as well be inlined.
+The only requirement on the value, is that it is a string that can be parsed as Action Language::
+
+    >>> instantiate_attr_code("my_fsa", "transition_1", "action", \
+    ...     """
+    ...     include "primitives.alh"
+    ...     Void function action(model : Element):
+    ...         log("Executed action!")
+    ...         return!
+    ...     """
+
+Action language attributes are considered identical to any other attribute.
+The exception is of course that they are assigned using the code specific function, as otherwise we would have uploaded a string.
+Note the difference between the assignment of a string, and the assignment of action code::
 
-There are two kinds of files: code files, and headers.
-This distinction is similar to C and related languages.
-Code in header files will always be copied throughout all including files.
-As such, it is a good idea to have header files which declare the signatures of functions, but leave the actual implementation to the code files.
-Code files do not need to import the headers they are implementing: all variable names are automatically shared.
+    >>> instantiate_attr("my_fsa", "transition_1", "action", open("actions/transition_1.alc", "r").read())
+    >>> instantiate_attr_code("my_fsa", "transition_1", "action", open("actions/transition_1.alc", "r").read())
+
+The first line assigns a string to the attribute, and is therefore not executable, nor is it parsed or considered in any way.
+The second line assigns code to the attribute, and is therefore executable, and parsed upon assignment.
+
+The signature of each function, in the case of our example this is "Void function action(model : Element)", depends on how the code will be used later on.
+
+Multi-function code
+-------------------
+
+Some code is ideally expressed using multiple functions.
+As the Modelverse does not support subfunctions, it supports the second best alternative: multiple functions can be defined.
+When multiple functions are defined, the *main* function will be executed, which can refer to any of the other functions defined in the same block.
+If no *main* function is found, the topmost function is executed.
 
 Language description
 --------------------
 
+Next we describe the basic constructs of the language, as offered by our compiler.
 The language is inspired by Python syntax, and highly resembles it.
 Nonetheless, it is a lot simpler.
 In the remainder of this subsection, we go over the different language constructs.
@@ -202,6 +241,7 @@ Include
 Other files can easily be included using the include syntax.
 This is a raw include: the contents of the file are just copied inside the file at that exact spot.
 Generally, you should only include *.alh* files, unless you know what you are doing.
+There is a set of standard header files included in the Modelverse, which are probably the only ones you will need.
 
 Constants
 ^^^^^^^^^
@@ -234,3 +274,135 @@ User input and output is done through the keyworded operations *input()* and *ou
 
 All I/O is done using queues: the value is only read and written to a specific place in the Modelverse.
 To actually read or write it at the client side, these special places should be accessed through dedicated Modelverse operations.
+
+Primitive operations
+^^^^^^^^^^^^^^^^^^^^
+
+Apart from the minimal syntax, the Modelverse supports a wide library of functions.
+These functions are all built on top of the previously defined constructs.
+A list of these functions is shown below.
+
+* Boolean function value_eq(a: Element, b: Element)
+* Boolean function value_neq(a: Element, b: Element)
+* Boolean function bool_and(a: Boolean, b: Boolean)
+* Boolean function bool_or(a: Boolean, b: Boolean)
+* Boolean function bool_not(a: Boolean)
+* Element function create_node()
+* Element function create_edge(a: Element, b: Element)
+* Element function create_value(a: Element)
+* Boolean function is_edge(a: Element)
+* Integer function read_nr_out(a: Element)
+* Element function read_out(a: Element, b: Integer)
+* Integer function read_nr_in(a: Element)
+* Element function read_in(a: Element, b: Integer)
+* Element function read_edge_src(a: Element)
+* Element function read_edge_dst(a: Element)
+* Boolean function delete_element(a: Element)
+* Boolean function element_eq(a: Element, b: Element)
+* Boolean function element_neq(a: Element, b: Element)
+* Float function cast_i2f(a: Integer)
+* String function cast_i2s(a: Integer)
+* Boolean function cast_i2b(a: Integer)
+* Integer function cast_f2i(a: Float)
+* Boolean function cast_f2b(a: Float)
+* String function cast_f2s(a: Float)
+* Integer function cast_s2i(a: String)
+* Float function cast_s2f(a: String)
+* Boolean function cast_s2b(a: String)
+* Integer function cast_b2i(a: Boolean)
+* Float function cast_b2f(a: Boolean)
+* String function cast_b2s(a: Boolean)
+* String function cast_e2s(a: Element)
+* String function cast_a2s(a: Action)
+* String function cast_v2s(a: Element)
+* String function cast_id2s(a: Element)
+* Element function dict_add(a: Element, b: Element, c: Element)
+* Element function dict_add_fast(a: Element, b: Element, c: Element)
+* Element function dict_delete(a: Element, b: Element)
+* Element function dict_delete_node(a: Element, b: Element)
+* Element function dict_read(a: Element, b: Element)
+* Element function dict_read_edge(a: Element, b: Element)
+* Element function dict_read_node(a: Element, b: Element)
+* Integer function dict_len(a: Element)
+* Boolean function dict_in(a: Element, b: Element)
+* Boolean function dict_in_node(a: Element, b: Element)
+* Element function dict_keys(a: Element)
+* Float function float_addition(a: Float, b: Float)
+* Float function float_subtraction(a: Float, b: Float)
+* Float function float_multiplication(a: Float, b: Float)
+* Float function float_division(a: Float, b: Float)
+* Float function float_neg(a: Float)
+* Boolean function float_gt(a: Float, b: Float)
+* Boolean function float_gte(a: Float, b: Float)
+* Boolean function float_lt(a: Float, b: Float)
+* Boolean function float_lte(a: Float, b: Float)
+* Integer function integer_addition(a: Integer, b: Integer)
+* Integer function integer_subtraction(a: Integer, b: Integer)
+* Integer function integer_multiplication(a: Integer, b: Integer)
+* Integer function integer_division(a: Integer, b: Integer)
+* Integer function integer_modulo(a: Integer, b: Integer)
+* Boolean function integer_gt(a: Integer, b: Integer)
+* Boolean function integer_gte(a: Integer, b: Integer)
+* Boolean function integer_lt(a: Integer, b: Integer)
+* Boolean function integer_lte(a: Integer, b: Integer)
+* Boolean function integer_neg(a: Integer)
+* Element function list_read(a: Element, b: Integer)
+* Element function list_append(a: Element, b: Element)
+* Element function list_insert(a: Element, b: Element, c: Integer)
+* Element function list_delete(a: Element, b: Integer)
+* Integer function list_len(a: Element)
+* Boolean function list_in(a : Element, b : Element)
+* Element function set_add(a: Element, b: Element)
+* Element function set_add_node(a: Element, b: Element)
+* Element function set_pop(a: Element)
+* Element function set_read(a : Element)
+* Element function set_remove(a: Element, b: Element)
+* Boolean function set_in(a: Element, b: Element)
+* Element function set_remove_node(a: Element, b: Element)
+* Element function set_in_node(a: Element, b: Element)
+* Integer function set_len(a: Element)
+* String function string_join(a: String, b: String)
+* String function string_get(a: String, b: Integer)
+* String function string_substr(a: String, b: Integer, c: Integer)
+* Integer function string_len(a: String)
+* Element function string_split(a: String, b: String)
+* Boolean function string_startswith(a: String, b: String)
+* String function log(a: String)
+* Element function read_root()
+* Element function read_taskroot()
+* Element function input()
+* Element function output(a : Element)
+* Boolean function is_physical_int(a : Element)
+* Boolean function is_physical_float(a : Element)
+* Boolean function is_physical_string(a : Element)
+* Boolean function is_physical_action(a : Element)
+* Boolean function is_physical_boolean(a : Element)
+* Boolean function has_value(a : Element)
+* Float function time()
+* String function hash(a : String)
+* Void function sleep(a : Float)
+* Void function interruptable_sleep(a : Float)
+* Element function exec(a : Element)
+* Element function resolve(var_name : String)
+* Boolean function has_input()
+* Element function list_pop(lst : Element, index : Integer)
+* Element function list_pop_final(lst : Element)
+* Element function set_copy(set : Element)
+* String function set_to_string(set : Element)
+* String function list_to_string(set : Element)
+* String function dict_to_string(dict : Element)
+* Element function set_overlap(sa : Element, sb : Element)
+* Element function set_equality(sa : Element, sb : Element)
+* Element function dict_eq(da : Element, db : Element)
+* Element function dict_copy(dict : Element)
+* Element function set_to_list(s : Element)
+* Element function create_tuple(a : Element, b : Element)
+* Void function dict_overwrite(a : Element, b : Element, c : Element)
+* Void function set_merge(sa : Element, sb : Element)
+* Element function make_reverse_dictionary(dict : Element)
+* Element function set_create()
+* Element function list_create()
+* Element function dict_create()
+* String function reverseKeyLookup(a: Element, b: Element)
+* Element function reverseKeyLookupMulti(a: Element, b: Element)
+* Element function dict_values(dict : Element)

+ 20 - 0
doc/bootstrap.rst

@@ -0,0 +1,20 @@
+Bootstrap
+=========
+
+Explain what the bootstrapping actually does
+
+Initial Code
+------------
+
+Explain the initial files and possibly link to them as well
+
+Initial Models
+--------------
+
+Explain the initial models and how they link together
+Explain the bootstrap compiler for models
+
+Altering the Bootstrap File
+---------------------------
+
+Explain how to alter bootstrap files and what needs to be done to change it

+ 25 - 0
doc/concrete_syntax.rst

@@ -0,0 +1,25 @@
+Concrete Syntax
+===============
+
+Explain concrete syntax and why we want to have it
++ refer to paper
+
+Defining Concrete Syntax
+------------------------
+
+Explain how we define concrete syntax in the Modelverse
+
+MM_Rendered
+^^^^^^^^^^^
+
+Explain how MM_Rendered looks like and what it can be used for
+
+Modelverse Client
+-----------------
+
+Explain the simple client, and why it can be minimal
+
+Modelverse Perceptualization
+----------------------------
+
+Explain perceptualization and how it communicates with the Modelverse

+ 5 - 5
doc/conf.py

@@ -49,7 +49,7 @@ master_doc = 'index'
 
 # General information about the project.
 project = u'Modelverse'
-copyright = u'2016, Yentl Van Tendeloo'
+copyright = u'2017, Yentl Van Tendeloo'
 author = u'Yentl Van Tendeloo'
 
 # The version info for the project you're documenting, acts as replacement for
@@ -57,9 +57,9 @@ author = u'Yentl Van Tendeloo'
 # built documents.
 #
 # The short X.Y version.
-version = u'0.6'
+version = u'0.7'
 # The full version, including alpha/beta/rc tags.
-release = u'0.6.1'
+release = u'0.7.1'
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
@@ -119,7 +119,7 @@ todo_include_todos = False
 # The theme to use for HTML and HTML Help pages.  See the documentation for
 # a list of builtin themes.
 #
-html_theme = 'classic'
+html_theme = 'default'
 
 # Theme options are theme-specific and customize the look and feel of a theme
 # further.  For a list of options available for each theme, see the
@@ -199,7 +199,7 @@ html_static_path = ['_static']
 
 # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
 #
-# html_show_sphinx = True
+html_show_sphinx = False
 
 # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
 #

+ 19 - 0
doc/conformance.rst

@@ -0,0 +1,19 @@
+Conformance
+===========
+
+Explain the conformance relation in the context of the Modelverse
+
+Multi-Conformance
+-----------------
+
+Explain the notion of multi-conformance and why it is useful
+
+Metamodel Finding
+-----------------
+
+Explain why we can do metamodel finding, and why we would like it
+
+Conformance Bottom
+------------------
+
+Explain the use of conformance bottom, and how it contributes in combination with metamodel finding, or finding a binding

+ 15 - 0
doc/developer.rst

@@ -0,0 +1,15 @@
+Using the Modelverse as a Developer
+===========================================
+
+.. toctree::
+   :maxdepth: 2
+
+   Scripts <scripts>
+   Wrappers <wrappers>
+   Model representation <model>
+   Modelverse components <components>
+   Communication models <communication_models>
+   Primitives <primitives>
+   Bootstrap <bootstrap>
+   Internals <internal>
+   Interfaces <interface>

+ 12 - 7
doc/index.rst

@@ -6,16 +6,21 @@
 Welcome to the Modelverse documentation!
 ========================================
 
-Contents:
+This document contains all practical information regarding the Modelverse.
+References to the papers describing the theoretical concepts are made throughout the documentation.
+As such, this document is a practical introduction to (meta-)modelling in the Modelverse.
+
+We make the distinction between three types of users of the Modelverse: modellers, language engineers, and developers.
+Depending on your goals of using the Modelverse, you will fall into one of these categories.
+Due to the design of the Modelverse, where everything is a model, the hierarchy is cumulative: language require knowledge of modelling, and developers require knowledge of language engineer and modelling.
 
 .. toctree::
    :maxdepth: 2
     
    Installation <installation>
-   How to run <howto>
-   Modelverse components <components>
-   Action Language <actionlanguage>
-   Modelling Language <modellanguage>
-   Wrappers <wrappers>
+   Basic interaction <interaction>
+   Types of user <users>
+   Modeller <modeller>
+   Language Engineer <language_engineer>
+   Developer <developer>
    Common problems and solutions <problems>
-   Internals <internal>

+ 33 - 38
doc/installation.rst

@@ -1,14 +1,33 @@
 Installation
 ============
 
+Installation of the Modelverse is rather simple, as is its simple usage.
+We first introduce the dependencies of the Modelverse, followed by installation instructions for the Modelverse itself.
+To check whether or not the installation was successful, users can run the enclosed tests.
+
 Dependencies
 ------------
 
 The Modelverse reference implementation is relatively dependency-free.
 As its code is written in Python 2, a working Python 2.7 interpreter is necessary.
-
-To run the tests, this interpreter needs to have the `pytest <http://docs.pytest.org/en/latest/>`_ module installed.
 To run the server, the `SCCD <https://msdl.uantwerpen.be/git/simon/SCCD>`_ module needs to be installed.
+Full installation instructions can be found on the project website.
+
+To run the tests, the `pytest <http://docs.pytest.org/en/latest/>`_ module must be installed.
+In case you want to use PyPy, which often offers increased performance, you need to install both dependencies in PyPy as well.
+Next, we document how this is done.
+
+PyPy
+^^^^
+
+For SCCD, you can simply install it using PyPy instead of CPython.
+
+For pytest, you also need to install all of pytest's dependencies, and pytest itself.
+The easiest way to do this is through *pip*, which you also have to install first for PyPy::
+
+    wget https://msdl.uantwerpen.be/files/get-pip.py
+    pypy get-pip.py --user
+    pypy -m pip install pytest --user
 
 Installation
 ------------
@@ -16,18 +35,18 @@ Installation
 The Modelverse is merely a set of Python scripts, and there is no real installation, except for its dependencies.
 As such, you will only have to download the source code and are ready to use the Modelverse.
 
-0. Install dependencies.
-1. Download the `Modelverse source code <https://msdl.uantwerpen.be/git/yentl/modelverse>`_.
-   For example using git::
+To install the Modelverse, download the `Modelverse source code <https://msdl.uantwerpen.be/git/yentl/modelverse>`_.
+This can be done through git::
 
     git clone https://msdl.uantwerpen.be/git/yentl/modelverse
 
-   Or using your favorite HTTP download tool::
+Or using your favorite HTTP download tool::
 
     wget https://msdl.uantwerpen.be/git/yentl/modelverse/archive/master.zip
     unzip master.zip
 
-2. That's it! You can now run the scripts in the *scripts/* directory using Python.
+You can now run the scripts in the *scripts/* directory using Python.
+In the next section, we go deeper into the relevant scripts.
 
 Tests
 -----
@@ -38,37 +57,13 @@ Executing the tests is as simple as the following command::
 
     python scripts/run_tests.py
 
-This will run a set of tests for all different projects.
-Note that this also causes some bootstrap files to be created, which might take some time on slow machines.
-A faster alternative is to only run the overall tests::
-
-    python -m pytest integration
-
-PyPy
-^^^^
-
-The default way of executing tests is probably through CPython.
-Note, however, that CPython is a slow implementation of Python, which makes everything in the Modelverse slower.
-While it is not impossible to use CPython, using PyPy is recommended for the server!
-Nonetheless, PyPy is often not the default interpreter.
-You will therefore have to explicitly give control to PyPy instead of CPython.
-
-This is fairly simple: all scripts in *scripts/* execute their subprocesses using the Python interpreter used to start the script.
-As such, the following command suffices to execute the Modelverse tests using PyPy::
-
-    pypy scripts/run_tests.py
+.. note::
 
-The problem, however, is that all modules need to be readily installed on PyPy.
-For SCCD, you can simply install it using PyPy instead of CPython.
-For pytest, you also need to install all of pytest's dependencies.
-The easiest way to do this is through *pip*, which you also have to install first::
+   If you prefer to use PyPy, you can similarly execute it by replacing *python* with *pypy*.
+   All occurences of *python* can be replaced by *pypy*, as long as both implement Python 2.7.
 
-    wget https://msdl.uantwerpen.be/files/get-pip.py
-    pypy get-pip.py --user
-    pypy -m pip install pytest --user
-
-Afterwards, you can simply run::
-
-    pypy scripts/run_tests.py
+This will run a set of tests for all different projects.
+Note that this also causes some bootstrap files to be created, which might take some time on slow machines, certainly if PyPy is not used.
+A faster alternative is to run the faster tests, though this will not test the creation of bootstrap files::
 
-To execute the tests using PyPy.
+    python scripts/run_fast_tests.py

+ 94 - 0
doc/interaction.rst

@@ -0,0 +1,94 @@
+Basic Interaction
+=================
+
+As previously mentioned during the installation phase, the Modelverse is merely a collection of scripts.
+We briefly present how the Modelverse is structured, and introduce the most important scripts for general use.
+A more elaborate view on the architecture and the different scripts is only required for developers of the Modelverse.
+
+Simplified Architecture
+-----------------------
+
+The Modelverse architecture consists of three core concepts, which will be referred to throughout the documentation.
+
+Modelverse State (MvS)
+^^^^^^^^^^^^^^^^^^^^^^
+
+The Modelverse State (MvS) is the memory of the Modelverse, and contains all data pertaining to it.
+This includes not only the different models created by the users, but also all metamodels, transformations, operations, but also all bootstrap files.
+Furthermore, it includes all execution state of operations being executed in the Modelverse.
+As such, the Modelverse State is the database of the Modelverse, which is the only component containing data.
+Only developers will ever have to directly interface with the Modelverse State.
+
+Modelverse Kernel (MvK)
+^^^^^^^^^^^^^^^^^^^^^^^
+
+The Modelverse Kernel (MvK) is the execution core of the Modelverse, and connects to the Modelverse State to fetch the instructions to execute.
+All its execution information is stored in the MvS as well, and therefore it has to (theoretically) query the MvS for each and every instruction.
+It merely consists of a set of model transformation rules which take the current state of the MvS, and do a set of modifications on it.
+Only developers will ever have to directly interface with the Modelverse Kernel.
+
+Modelverse Interface (MvI)
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The Modelverse Interface (MvI) is the actual interface used by most users of the Modelverse.
+It provides any type of interface, whether it be graphical, textual, or any other interface.
+While this is the component that users interact with, there should be no (meta-)modelling knowledge whatsoever in this part, as it is only responsible for providing a user-friendly interface to the Modelverse.
+This component can make use of the provided wrapper, which does the binding with the Modelverse.
+
+Necessary scripts
+-----------------
+
+The Modelverse consists of a set of scripts.
+For most users, there are only three relevant scripts, none of them taking parameters:
+
+1. *run_tests.py*, which runs all tests.
+2. *run_local_modelverse.py*, which starts up a local Modelverse server, combining the MvS and MvK.
+3. *prompt.py*, which connects to the local Modelverse and provides a minimal raw interface.
+
+Wrapper
+-------
+
+In addition to these scripts, we provide a simple Python-based wrapper for the Modelverse.
+As the Modelverse can run as a service, wrappers can be created in any language that supports XML/HTTPRequests.
+By default, a Python wrapper is provided, which is discussed in this documentation.
+This Python wrapper was used by a variety of MvI implementations supported today.
+Tools can include all Modelverse operations merely by including the *modelverse.py* file from the *wrappers* folder.
+
+The wrapper provides all necessary (meta-)modelling operations that can be used by the MvI.
+As the Modelverse is independent of its (visual/textual) user interface, we only discuss the Modelverse wrapper in this documentation.
+The wrapper functions are explained through the use of examples, in a tutorial-like fashion.
+A full overview of all wrapper functions is also provided at the end of the documentation.
+
+Initializing the Modelverse
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Before we start, we must connect to the Modelverse.
+This can be done by executing the operation *init*::
+
+    >>> init("http://modelverse.uantwerpen.be")
+
+This assumes that there is a Modelverse running at the specified address.
+It is also possible to work fully locally.
+For that, you must start up a Modelverse at your own system by invoking the command::
+
+    python scripts/run_local_modelverse.py
+
+Afterwards, connect to the local Modelverse through the usual *init* operation.
+Note that, for a local Modelverse, the init can be left empty::
+
+    >>> init()
+
+Logging in
+^^^^^^^^^^
+
+Now that we are connected to the Modelverse, we need to log in.
+Without logging in, the Modelverse has no clue which operations are permitted, and which models are readable, or even writable.
+To log in, use the *login* operation::
+
+    >>> login("yentl", "secret password")
+
+The operation will succeed if it terminates normally, and throw a Python exception otherwise.
+When the username does not exist yet, it is created upon invocation.
+The provided password can be used in subsequent invocations of the Modelverse to login as this user again.
+
+If this command finished successfully, the Modelverse is ready to be used.

+ 3 - 3
doc/internal.rst

@@ -166,14 +166,14 @@ The initial graph consists of several parts:
 
 * The Modelverse Root node;
 * A global definition of all primitives;
-* The stack frame of the initial user *user_manager*, which manages all other users;
-* The code for the *user_manager* user;
+* The stack frame of the initial task *task_manager*, which manages all other tasks;
+* The code for the *task_manager* task;
 * The code for all new users, as assigned by the *user_manager*;
 * Bindings in the compilation manager for bootstrap files.
 
 These are all fairly simple in themselves.
 For some parts, such as the code, the HUTN compiler is invoked on a temporary piece of code.
-All bootstrap files are also compiled and made available to the compilation manager with their MD5 hash.
+All bootstrap files are also compiled and made available to the Modelverse.
 
 How to add a primitive
 ----------------------

+ 18 - 0
doc/language_engineer.rst

@@ -0,0 +1,18 @@
+Using the Modelverse as a Language Engineer
+===========================================
+
+With all the modelling primitives given, the next step is to actually create the languages that were used before: how were the *PetriNets* and *FiniteStateAutomata* language defined?
+This is the job of the language engineer, who will create these languages through modelling as well.
+Indeed, everything in the Modelverse is explicitly modelled, including languages.
+When defining a language, the language engineer will mostly use the same operations as the modeller, though in a different context.
+
+.. toctree::
+   :maxdepth: 2
+
+   Metamodelling <metamodelling>
+   Model Langugage <languageengineer_modellanguage>
+   Transformations <transformations>
+   Operations <operations>
+   Services <services>
+   Concrete Syntax <concrete_syntax>
+   Conformance <conformance>

+ 103 - 0
doc/languageengineer_modellanguage.rst

@@ -0,0 +1,103 @@
+Modelling Language
+==================
+
+We now revisit the modelling language.
+All concepts defined for modellers, are equally valid for language engineers.
+Indeed, language engineering is a specific type of modelling.
+
+The only real extension that we need to make, is to extend the syntax with a specific construct to define a generalization hierarchy and attributes.
+
+Generalization
+--------------
+
+The first concept is that of generalization.
+As expected, a class can inherit from another class through the intuitive notation::
+
+    Class NamedElement {}
+    Class Place : NamedElement {}
+    Class Transition : NamedElement {}
+
+What is special in the Modelverse, is that associations can just as well inherit from one another::
+
+    Association Arc (NamedElement, NamedElement) {}
+    Association P2T : Arc (Place, Transition) {}
+    Association T2P : Arc (Transition, Place) {}
+
+Attributes
+----------
+
+Attributes can still be created using only modelling constructs, as introduced before, though this becomes convoluted.
+More efficiently, the attribute can be defined as follows.
+Note that, thanks to inheritance, the *Place* and *Transition* can also access the *name* attribute, as they inherit it.
+The *NamedElement* can now be defined as follows::
+
+    Class NamedElement{
+        name : String
+    }
+
+Note that now as well, it is necessary to define the types.
+This can just be done as expected::
+
+    SimpleAttribute String {
+        constraint = $
+            String function constraint(value : Element):
+                if (is_primitive_string(value)):
+                    return "OK"!
+                else:
+                    return "String has a non-string value"!
+            $
+    }
+
+Finally, it is possible to define an *optional* attribute.
+In that case, the attribute must not be defined, though you should be aware that reading an undefined attribute will result in an error value being returned.
+Default values are not supported in the Modelverse.
+This is done by using the following notation to make the attribute optional::
+
+    Class NamedElement {
+        name? : String
+    }
+
+A Petri Net metamodel can now be created, based on the SimpleClassDiagrams metamodel.
+This looks like this::
+
+    include "primitives.alh"
+
+    SimpleAttribute String {
+        constraint = $
+            String function constraint(value : Element):
+                if (is_primitive_string(value)):
+                    return "OK"!
+                else:
+                    return "String has a non-string value"!
+            $
+    }
+
+    SimpleAttribute Natural {
+        constraint = $
+            String function constraint(value : Element):
+                if (bool_not(is_physical_int(value))):
+                    return "Natural has no integer value"!
+                elif (integer_lt(value, 0)):
+                    return "Natural does not have a positive or zero value"!
+                else:
+                    return "OK"!
+            $
+    }
+
+    Class NamedElement {
+        name : String
+    }
+
+    Class Place : NamedElement {
+        tokens : Natural
+    }
+
+    Class Transition : NamedElement {}
+
+    Association Arc (NamedElement, NamedElement) {
+        weight : Natural
+    }
+
+    Association P2T : Arc (Place, Transition) {}
+
+    Association T2P : Arc (Transition, Place) {}

+ 184 - 0
doc/metamodelling.rst

@@ -0,0 +1,184 @@
+Metamodelling
+=============
+
+Defining languages in the Modelverse is done through metamodelling.
+With metamodelling, a language is itself a model, which can be created through the usual operations.
+This explains why language engineers need to have the same knowledge of the Modelverse as modellers: language engineering is modelling in a domain-specific language for languages.
+
+Creating a metamodel
+--------------------
+
+To create a metamodel, you have to instantiate the *SimpleClassDiagrams* metamodel.
+While there is no restriction that this has to be *SimpleClassDiagrams*, for now we assume that this is the only possible meta-language.
+Therefore, to create the PetriNets language, we execute::
+
+    >>> model_add("PetriNets", "SimpleClassDiagrams")
+
+From then on, we can simply use the PetriNets metamodel as if it were a model.
+Again, the *model_add* operation can take an optional third parameter, specifying the textual representation of the model.
+We will go deeper into this in one of the next sections.
+
+Instantiating a metamodel
+-------------------------
+
+To actually define a metamodel, we need to add elements to it.
+These elements are tightly related to the metamodel of the model, being most likely *SimpleClassDiagrams*.
+In this language, there exist four major components: *Class*, *Association*, *Inheritance*, and attributes.
+
+Class
+^^^^^
+
+Creating a class is easy, and very similar to usual modelling.
+To define the *Place* concept, which can later on be used in models, we merely define this as a new class::
+
+    >>> instantiate("PetriNets", "Class", ID="Place")
+
+Note that here we must define an ID to get a sensible name to use.
+Of course, this ID does not need to be used, and the returned (randomized) ID can just as well be used.
+Nonetheless, if it is used, it becomes non-intuitive to use in future requests.
+In the instance of this newly created language, we can immediately use the new concept::
+
+    >>> instantiate("PetriNets", "Class", ID="Place")
+    >>> instantiate("my_pn", "Place")
+
+If the ID was not used, we must remember the ID that was provided to us::
+
+    >>> pn_place = instantiate("PetriNets", "Class")
+    >>> instantiate("my_pn", pn_place)
+
+While this is more reliable, it becomes difficult to refer to the concept in the future without any clue as to what it resembles.
+Later on, this can be solved with concrete syntax, in which case modellers can identify the concepts based on their visual representation.
+
+Association
+^^^^^^^^^^^
+
+Creating a link between two concepts is very similar.
+For example, to create the *P2T* association, merely create an instance of association, using the same remarks as before::
+
+    >>> instantiate("PetriNets", "Association", edge=("Place", "Transition"), ID="P2T")
+
+Inheritance
+^^^^^^^^^^^
+
+A useful concept is the use of inheritance, whereby the inheriting class can take on the responsibilities of the inherited class.
+To create this, simply instantiate the *Inheritance* association as usual.
+For example, it is possible to structure the *PetriNets* model (in an admittedly strange way) such that there is a generic concept of *NamedElement* and *Arc*::
+
+    >>> instantiate("PetriNets", "Class", ID="NamedElement")
+    >>> instantiate("PetriNets", "Class", ID="Place")
+    >>> instantiate("PetriNets", "Class", ID="Transition")
+    >>> instantiate("PetriNets", "Inheritance", edge=("Place", "NamedElement"))
+    >>> instantiate("PetriNets", "Inheritance", edge=("Transition", "NamedElement"))
+
+In the Modelverse, inheritance is possible between any two instances, including associations.
+To define the *Arc* relation, we act similar::
+
+    >>> instantiate("PetriNets", "Association", edge=("NamedElement", "NamedElement"), ID="Arc")
+    >>> instantiate("PetriNets", "Association", edge=("Place", "Transition"), ID="P2T")
+    >>> instantiate("PetriNets", "Association", edge=("Transition", "Place"), ID="T2P")
+    >>> instantiate("PetriNets", "Inheritance", edge=("P2T", "Arc"))
+    >>> instantiate("PetriNets", "Inheritance", edge=("T2P", "Arc"))
+
+Instantiating attributes
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Instantiating attributes is similar as it was before::
+
+    >>> attr_assign("PetriNets", "NamedElement", "name", "NamedElement")
+    >>> attr_assign("PetriNets", "Transition", "name", "Transition")
+    >>> attr_assign("PetriNets", "Place", "name", "Place")
+
+Note that this *name* attribute is in no way related to the *name* attributes at the *my_pn* level.
+Indeed, the *name* in *PetriNets* specifies the name of the class.
+Other attributes that can be set on classes are:
+
+1. *lower_cardinality* specifies the number (integer) of instances that must at least exist of this element.
+2. *upper_cardinality* specifies the number (integer) of instances that must at most exist of this element.
+3. *constraint* specifies additional constraints on the instances of this class.
+
+For associations, we have the same three attributes, augmented with:
+
+4. *source_lower_cardinality* specifies the number (integer) of incoming edges that are at least required for the target.
+5. *source_upper_cardinality* specifies the number (integer) of incoming edges that are at most required for the target.
+6. *target_lower_cardinality* specifies the number (integer) of outgoing edges that are at least required for the source.
+7. *target_upper_cardinality* specifies the number (integer) of outgoing edges that are at most required for the source.
+
+Constraints
+^^^^^^^^^^^
+
+A constraint specifies additional constraints on the instances of this model, which could not be expressed before.
+We distinguish between two types of constraints: local and global constraints.
+
+Local constraints are defined at the level of a single class or association.
+For example, if the number of tokens must always be non-negative, this can be specified as follows::
+
+    >>> attr_assign_code("PetriNets", "Place", "constraints", \
+    ...     """
+    ...     String function constraint(model : Element, name : String):
+    ...         if (integer_gte(read_attribute(model, name, "tokens"), 0)):
+    ...             return "OK"!
+    ...         else:
+    ...             return "Negative number of tokens specified"!
+
+Global constraints operate over the complete model, and are therefore not attached to a single element.
+Instead, a specific *GlobalConstraint* element must be instantiated.
+This element has a *constraint* attribute, which specifies the constraint to evaluate in the global context.
+For example, when, for some reason, the number of places must always be larger than the number of transitions::
+
+    >>> constraint = instantiate("PetriNets", "GlobalConstraint")
+    >>> attr_assign_code("PetriNets", constraint, "constraint", \
+    ...     """
+    ...     String function constraint(model : Element):
+    ...         if (set_len(allInstances(model, "Place")) > set_len(allInstances(model, "Transition"))):
+    ...             return "OK"!
+    ...         else:
+    ...             return "Needs more places than transitions"!
+
+While all constraints can be specified as global constraints, using local constraints is preferred.
+
+.. note::
+   Currently, all constraints are only evaluated upon explicit user request.
+   More specifically: during the *verify* operation.
+
+Defining attributes
+^^^^^^^^^^^^^^^^^^^
+
+Defining attributes is an important consideration in a metamodel.
+Up to now, our *Place* and *Transition* were just nodes without any attributes.
+A meaningful (marked) petrinet has tokens in places, and names for the places and transitions.
+To define these attributes, we must take two steps:
+
+1. Define the type that will be used (e.g., String, Integer)
+2. Define the name and type of the attribute (e.g., *tokens* is an Integer, *name* is a String)
+
+To define the type that we want to use, we must manually define it.
+While many other tools provide a set of primitives, which cannot be altered in any way, the Modelverse leaves all this up to the language engineer.
+If the language engineer wants the concepts of a *Natural*, for example, it is not required that the attribute is specified as an Integer, with an additional constraint on each and every attribute that is defined this way.
+It is possible to define a new attribute type as follows::
+
+    >>> instantiate("PetriNets", "SimpleAttribute", ID="Natural")
+
+But now, the attribute is constrained in no way: it is merely called Natural, but can even contain a string.
+The attribute type must be constrained::
+
+    >>> attr_assign_code("PetriNets", "Natural", "constraint", \
+    ...     """
+    ...     String function constraint(value : Element):
+    ...         if (is_physical_integer(value)):
+    ...             if (integer_geq(value, 0)):
+    ...                 return "OK"!
+    ...             else:
+    ...                 return "Not a positive value"!
+    ...         else:
+    ...             return "Not a numeric value!"!
+
+Now, the *Natural* is correctly specified and can be used throughout the model.
+All uses of *Natural* will now make sure that the value is positive.
+This offers additional possibilities, such as defining complex attributes as if they were primitives, for example complex numbers.
+
+The next step is to define the attribute itself.
+This can be easily done as follows::
+
+    >>> define_attribute("PetriNets", "Place", "tokens", "Natural")
+
+For the name, *String* can be defined similarly (using *is_physical_string*).

+ 0 - 98
doc/mini_modify.rst

@@ -1,98 +0,0 @@
-Model Modification Interface
-============================
-
-Model operations are grouped into a separate category of operations, as they work at the model-level instead of the root-level.
-In the MvC, these operations can only be executed after a *model_modify* operation.
-We distinguish two modes of access: read/write, and read-only.
-Read-only commands are always available (given that the model itself can be opened in the MvC layer), whereas read/write operations are only optionally visible.
-
-Read-only
----------
-
-The first set of operations are the read-only operations.
-
-list
-^^^^
-
-Get a list of all elements in the model.
-Ignores hidden elements (*i.e.*, name starts with __), as these are artefacts of other operations.
-
-list_full
-^^^^^^^^^
-
-Get a full list of all elements in the model.
-
-nice_list
-^^^^^^^^^
-
-Get a pretty-printed list of alle elements in the model, including the value of their attributes.
-
-types
-^^^^^
-
-Get a list of all elements that can be instantiated in the metamodel.
-Ignores hidden elements of the metamodel.
-
-read
-^^^^
-
-Get detailed information on a specific element.
-
-verify
-^^^^^^
-
-Check if the model conforms to its resolved metamodel.
-
-exit
-^^^^
-
-Exit the model modification interface.
-
-Read/Write
-----------
-
-The second set of operations are the read/write operations, which are able to alter the model.
-Note that in the Modelverse, changes are immediately visible to other users as well.
-
-instantiate
-^^^^^^^^^^^
-
-Instantiate an element of the metamodel.
-This only creates the raw element, without any of its slots filled in or any associations.
-Used for both nodes and edges (classes and associations).
-
-delete
-^^^^^^
-
-Delete an element of the model.
-For nodes (classes), all related associations are removed as well.
-
-attr_add
-^^^^^^^^
-
-Instantiate a new attribute for this element.
-
-attr_add_code
-^^^^^^^^^^^^^
-
-Instantiate a new attribute for this element, using the code constructors for the value.
-
-attr_del
-^^^^^^^^
-
-Remove an attribute value of this element.
-
-attr_modify
-^^^^^^^^^^^
-
-Modify an existing attribute of this element.
-
-retype
-^^^^^^
-
-Change the type of an element.
-
-upload
-^^^^^^
-
-Overwrite the current model with an uploaded model through the model constructors.

+ 4 - 0
doc/model.rst

@@ -0,0 +1,4 @@
+Model representation
+====================
+
+Documents the internal model representation and provides remarks.

+ 0 - 209
doc/modellanguage.rst

@@ -1,209 +0,0 @@
-Modelling Language
-==================
-
-Apart from the action language, the Modelverse also has a modelling language.
-With this language, models (*i.e.*, data) can be defined in addition to the algorithms.
-
-This language is still work in progress, but should be decent enough to construct simple metamodels and instantiate them.
-All models have the extension \*.mvc, indicating that they are models and should be compiled as such.
-
-If you want to create models interactively, such as with another tool, it is strongly recommended to use the interactive interface to do this, as the modelling language is completely static.
-
-Language description
---------------------
-
-The modelling language defines data structures, which will be formed as models in the Modelverse.
-
-Several constructs are supported.
-
-Include
-^^^^^^^
-
-When combined with action language, for example with code fragments, the action language might require some includes of header files.
-To do this, the includes can be placed at the top of the hierarchy.
-The structure is as follows::
-
-        include "primitives.alh"
-
-Model
-^^^^^
-
-Every model is defined by first specifying the type of model to instantiate, followed by the name of the model to create.
-The name of the model can then later on be referenced in other models (as type, or for exporting).
-Within the model, all names of the type model can be used as types again.
-This is only used internally for bootstrapping purposes, so feel free to write whatever you want here.
-
-The structure is as follows::
-
-        SimpleClassDiagrams PetriNets{
-                ...
-        }
-
-All further operations happen inside such a definition.
-
-Instance
-^^^^^^^^
-
-A model consists of some instances.
-These instances are instances of types specified by the model that is the metaclass of the current model.
-
-The structure is as follows::
-
-        SimpleClassDiagrams PetriNets {
-                Class Place {
-                        ...
-                }
-        }
-
-Attribute
-^^^^^^^^^
-
-Each model instance can contain attributes.
-There are two kinds of attributes: defining attributes, or value attributes.
-
-For defining attributes, the structure is as follows::
-
-    Class A{
-        my_parameter : ParameterType
-    }
-
-This defines a parameter called *my_parameter* which is typed by *ParameterType*.
-*ParameterType* must always be a type defined in the type that is being instantiated.
-Even if this is a primitive, such as *Integer*, the metamodel must define what it calls an *Integer*.
-While this might seem bothersome, this clearly defines the notion of what a type means, without having to resort to the implementation.
-
-Value attributes are similar, but have a different syntax, and contain an actual value.
-Their structure is as follows::
-
-    A a{
-        my_parameter = 1
-    }
-
-They assign a value to a previously defined attribute.
-In this case, it is important that the value conforms to the type specified in the defining attribute.
-
-Merge with Action Language
---------------------------
-
-It is of course possible to incorporate action language inside of a model.
-A typical use case for this is the definition of constraints or actions.
-Action language is surrounded by dollar signs ($), which causes the parser to redirect the text between dollar signs to the action language parser.
-All includes necessary for the compilation of the action code, must be provided at the top of the document.
-
-Examples
---------
-
-Some simple examples of models are provided below.
-This code only makes the specified models available in code; to do something with these models, an algorithms has to read out the model and operate on it.
-
-Petri Net metamodel
-^^^^^^^^^^^^^^^^^^^
-
-A simple Petri Net metamodel can be created, based on the SimpleClassDiagrams metamodel.
-This looks like this::
-
-    import models/SimpleClassDiagrams as SCD
-
-    SCD PetriNets{
-        SimpleAttribute Natural {}
-        Class Place{
-            tokens : Natural
-        }
-        Class Transition{}
-        Association P2T (Place, Transition) {
-            weight : Natural
-        }
-        Association T2P (Transition, Place) {
-            weight : Natural
-        }
-    }
-
-    export PetriNets to models/PetriNets
-
-Note that in this metamodel, there is no constraint placed on the value of a Natural: it can literaly be anything.
-That is why usually, you want to place constraints on the value.
-In this case, the value needs to be an integer, and it must be larger than or equal to zero.
-Such constraints are written in the action language, surrounded by dollar signs::
-
-    import models/SimpleClassDiagrams as SCD
-    include "primitives.alh"
-
-    SCD PetriNets{
-        SimpleAttribute Natural {
-            $
-                if (bool_not(is_physical_int(self))):
-                    return "Natural has no integer value at " + name!
-                elif (integer_lt(self, 0)):
-                    return "Natural does not have a positive or zero value at " + name!
-                else:
-                    return "OK"!
-             $
-        }
-        Class Place{
-            tokens : Natural {
-                target_lower_cardinality = 1
-                target_upper_cardinality = 1
-                }
-        }
-        Class Transition{}
-        Association P2T (Place, Transition) {
-            weight : Natural {
-                target_lower_cardinality = 1
-                target_upper_cardinality = 1
-                }
-        }
-        Association T2P (Transition, Place) {
-            weight : Natural {
-                target_lower_cardinality = 1
-                target_upper_cardinality = 1
-                }
-        }
-    }
-
-Petri Net instance
-^^^^^^^^^^^^^^^^^^
-
-The previous metamodel can then be instantiated::
-
-    import models/PetriNets as PetriNets
-
-    PetriNets my_petrinet {
-        Place p1 {
-            tokens = 1
-        }
-        Place p2 {
-            tokens = 3
-        }
-        Transition t1 {}
-        P2T (p1, t1) {
-            weight = 1
-        }
-        T2P (t1, p2) {
-            weight = 2
-        }
-    }
-
-    export my_petrinet to models/my_petrinet
-
-Use in interactive interface
-----------------------------
-
-The interactive interface, such as the *prompt.py* script, can also invoke the model compiler.
-In this case, however, the import, export, and model type and model name parameters are ignored as they have to be defined and checked in the bigger context of the MvC.
-
-Internal use only
------------------
-
-Some constructs only make sense in the context of the bootstrap generation.
-These constructs can still be used at all times, but are meaningless.
-
-Import
-^^^^^^
-
-An import pulls in a model and makes it accessible using a simpler identifier.
-The structure is as follows::
-
-    import path/in/modelverse as my_model
-
-After this import, the model that was previously exported to *path/in/modelverse* becomes available as *my_model*.
-

+ 16 - 0
doc/modeller.rst

@@ -0,0 +1,16 @@
+Using the Modelverse as a Modeller
+==================================
+
+The first category of users that we consider, is that of a modeller.
+Whatever category a user falls in, this section is useful as it introduces the basic concepts of modelling using the Modelverse.
+
+In this section, we introduce users to modelling in the Modelverse, basic modelling permissions, and process enactment.
+
+.. toctree::
+   :maxdepth: 2
+
+   Modelling <modelling>
+   Permission system <permissions>
+   Action Langugage <actionlanguage>
+   Model Langugage <modeller_modellanguage>
+   Process Enactment <process_enactment>

+ 186 - 0
doc/modeller_modellanguage.rst

@@ -0,0 +1,186 @@
+Modelling Language
+==================
+
+Apart from the action language, the Modelverse also has a modelling language.
+With this language, models (*i.e.*, data) can be defined in addition to the algorithms.
+
+This language is still work in progress, but should be decent enough to construct simple models.
+All models have the extension \*.mvc, indicating that they are models and should be compiled as such.
+There is no constraint that this extension is mandatory.
+
+First, we show an example on how to create a simple PetriNet model.
+To take into account action language in the example model, we will also show an example for Finite State Automata.
+
+Example: Petri Nets
+-------------------
+
+Creating a simple Petri Net is easy using the Modelverse modelling language.
+An example is given below, which contains some places and transitions, with some connections between them::
+
+    Place p1 {
+        name = "place 1"
+        tokens = 1
+    }
+
+    Place p2 {
+        name = "place 2"
+        tokens = 2
+    }
+
+    Transition t1 {
+        name = "transition"
+    }
+
+    P2T p2t (p1, t1) {
+        weight = 1
+    }
+
+    T2P t2p (t1, p2) {
+        weight = 2
+    }
+
+The name immediately after the type (e.g., *p1*), is the identifier used throughout the textual representation.
+All identification of the element at the model-level should happen based on defined attributes.
+The identifiers can also be overwritten internally, in which case the latest definition is used.
+Do note that there is no concept of scope here, so identifiers stay visible throughout the whole file.
+It is possible to have anonymous identifiers, but only if the identifier is actually never used.
+For example, the two arcs could just as well have been defined as follows ::
+
+    P2T (p1, t1) {
+        weight = 1
+    }
+
+    T2P (t1, p2) {
+        weight = 2
+    }
+
+Example: Finite State Automata
+------------------------------
+
+Next we use a simple Finite State Automata example model.
+This will introduce two new concepts: hierarchy and code attributes.
+
+Hierarchy
+^^^^^^^^^
+
+The Modelverse does not natively support a notion of hierarchy, but its modelling language can easily be used to represent hierarchy.
+Models can be indented, which means that a link is created from the container to the containee.
+If only one link type is allowed between both, the type is automatically selected.
+If multiple link types are possible, it is ambiguous and the model will fail to compile.
+For example, if we consider a hierarchical state::
+
+    CompositeState s1 {
+        name = "state 1"
+
+        CompositeState s2 {
+            name = "state 2"
+
+            State s3 {
+                name = "state 3"
+            }
+        }
+    }
+
+    State s4 {
+        name = "state 4"
+    }
+
+When the only allowed links between a *CompositeState* and any other state is this, the model will compile fine as it is.
+However, we also want to define transitions, which can go from a *CompositeState* to a normal *State* as well.
+As such, we must update the model as follows, specifying the association type::
+
+    CompositeState s1 {
+        name = "state 1"
+
+        {Contains} CompositeState s2 {
+            name = "state 2"
+
+            {Contains} State s3 {
+                name = "state 3"
+            }
+        }
+    }
+
+    State s4 {
+        name = "state 4"
+    }
+
+As there is no difference between *Contains* and *Transition*, there is nothing that prevents you from creating something like::
+
+    State s1 {
+        name = "state 1"
+
+        {Transition} State {
+            name = "state 2"
+        }
+
+        {Contains} State {
+            name = "state 3"
+        }
+    }
+
+In this case, the state *state 1* and *state 2* are actually at the same level, with a transition between them.
+This can get rather confusing, and is therefore discouraged.
+
+Code
+^^^^
+
+Using code in the model definition is easy, and merely requires the use of the $ symbol around the text, instead of the usual " symbols.
+For example, to define a Transition with an action::
+
+    State s1 {
+        name = "state 1"
+    }
+
+    State s2 {
+        name = "state 2"
+    }
+
+    Transition (s1, s2) {
+        action = $
+            include "primitives.alh"
+            Void function action(model : Element):
+                log("Test!")
+                return !
+            $
+    }
+
+In this case, it is impossible to use code defined externally.
+All code between $ symbols is passed on as-is to the action language compiler.
+
+Note the import statements, which will likely be repeated in each and every code block.
+It is possible to define include statements at the top of the model, in which case the include is automatically prepended in each and every code block::
+
+    include "primitives.alh"
+
+    State s1 {
+        name = "state 1"
+    }
+
+    State s2 {
+        name = "state 2"
+    }
+
+    Transition (s1, s2) {
+        action = $
+            Void function action(model : Element):
+                log("Test!")
+                return !
+            $
+    }
+
+Using the Model Representation
+------------------------------
+
+The question remains how to use this model representation with the Modelverse.
+The *model_add* operation can be extended with an additional parameter, specifying a textual model.
+It will then create a new model and initialize it with the model specified textually::
+
+    >>> model_add("my_pn", "PetriNets", open("my_pn.mvc", "r").read())
+
+Another function that can be used, is the *model_overwrite* function, which overwrites an existing model with the content of the provided textual model::
+
+    >>> model_overwrite("my_pn", "PetriNets", open("my_pn.mvc", "r").read())
+
+Note that *model_overwrite* can also be used without the textual model parameter, in which case it will clear the specified model.
+That is, overwrite the model with an empty model.

+ 189 - 0
doc/modelling.rst

@@ -0,0 +1,189 @@
+Modelling
+=========
+
+Modelling is the core activity in the Modelverse.
+A model is based on a meta-model, or a language, which, for the sake of this tutorial, assume to exist.
+Throughout this tutorial, we will focus on how to instantiate a simple Petri Net model.
+We assume that our language has a notion of *Place*, *Transition*, *P2T* arc, and *T2P* arc.
+The *Place* has a *name* and *tokens*, the *Transition* has a *name*.
+Both the *P2T* and *T2P*"arcs have a *weight*.
+This information is stored in the metamodel, which we will define later on.
+For now, assume that the metamodel is stored in the Modelverse using the name *PetriNets*.
+
+Creating a model
+----------------
+
+Creating a new instance of PetriNets is simple, and can be done using the *model_add* operation of the wrapper::
+
+    >>> model_add("my_pn", "PetriNets")
+
+The first parameter of the operation indicates the name that we would like to give to our newly created model.
+This name is available to all users, and is therefore a unique identifier.
+The second parameter is the metamodel that we want to use to conform to.
+The value needs to be a name that is available in the Modelverse, and readable to the current user.
+
+To get a list of currently available models, users can query the Modelverse with the *model_list* operation::
+
+    >>> model_list()
+    [("PetriNets", "SimpleClassDiagrams"), ("SimpleClassDiagrams", "SimpleClassDiagrams"), ("ProcessModel", "SimpleClassDiagrams"), ...]
+
+This list contains the various models, and the metamodel of these models.
+Note that this operation does not specify anything about the permissions of the supplied models.
+
+Modifying a model
+-----------------
+
+Now that we have created our model, we can start modifying it.
+To do so, we have access to several operations offered by the Modelverse.
+We categorize them by their effects on the Modelverse: create, read, or delete.
+Create and delete operations are only allowed when the user has write permission to the model, which users have by default on their own models.
+
+Create
+^^^^^^
+
+1. *instantiate* creates a new instance in the model, for example a new PetriNet place::
+
+        >>> instantiate("my_pn", "Place")
+        __12345
+
+    The operation requires the model on which we are working, and the type of the element you want to instantiate.
+    When successful, the operation returns the identifier that can be used in future operations.
+    This identifier has no value within the model, and should only be used as a handle to that specific model element.
+
+    When instantiating an edge, the optional *edge* parameter must be passed with the identifiers to connect::
+        
+        >>> instantiate("my_pn", "Place")
+        p1
+        >>> instantiate("my_pn", "Transition")
+        t1
+        >>> instantiate("my_pn", "P2T", edge=("p1", "t1"))
+        p2t1
+
+2. *attr_assign* assigns attributes of a specific model element.
+   For example, it specifies the name and number of tokens of our PetriNet place::
+   
+        >>> instantiate("my_pn", "Place")
+        p1
+        >>> attr_assign("my_pn", "p1", "name", "place 1")
+        >>> attr_assign("my_pn", "p1", "tokens", 2)
+
+   The value of the attribute can be any simple primitive: string, integer, float, or boolean.
+   When the attribute already exists, its value is overwritten.
+   If it doesn't exist, it is created.
+
+Read
+^^^^
+
+1. *read* reads out basic information about a queried element, such as its type and the source and target (if it is an edge)::
+
+        >>> instantiate("my_pn", "Place")
+        p1
+        >>> read("my_pn", "p1")
+        ("Place, None)
+        >>> instantiate("my_pn", "Transition")
+        t1
+        >>> instantiate("my_pn", "P2T", edge=("p1", "t1"))
+        p2t1
+        >>> read("my_pn", "p2t1")
+        ("P2T", ("p1", "t1"))
+
+2. *read_attrs* reads out the attributes of a specific element, in a dictionary form.
+   This operation can be used to read out, for example, the number of tokens of a specific place::
+
+        >>> instantiate("my_pn", "Place")
+        p1
+        >>> attr_assign("my_pn", "p1", "name", "place 1")
+        >>> attr_assign("my_pn", "p1", "tokens", 2)
+        >>> read_attrs("my_pn", "p1")
+        {"name": "place 1", "tokens": 2}
+   
+3. *types* reads out the list of types that can be instantiated in this model.
+   All calls to instantiate should act upon one of these types.
+   For PetriNets, this returns the concepts of the domain::
+
+        >>> types()
+        ["Place", "Transition", "P2T", "T2P", ...]
+
+4. *element_list_nice* reads out a simple JSON-like representation of the model.
+   This includes all information about the model and can be used to fetch the complete model in one go.
+   For example, to read out a simple PetriNet::
+
+        >>> element_list_nice("my_pn")
+        [{"id": "p1", "type": "Place", "name": "place 1", "tokens": 1},
+         {"id": "p2", "type": "Place", "name": "place 2", "tokens": 2},
+         {"id": "t1", "type": "Transition"},
+         {"id": "p2t", "type": "P2T", "__source": "p1", "__target": "t1", "weight": 1},
+         {"id": "t2p", "type": "T2P", "__source": "t1", "__target": "p2", "weight": 2},
+        ]
+
+5. *read_outgoing* reads the outgoing associations of a certain type, for a specific element.
+   This takes into account inheritance relation.
+   For example, to read out all outgoing P2T links of a place::
+
+        >>> read_outgoing("my_pn", "p1", "P2T")
+        ["p2t"]
+
+   It is possible to get all outgoing associations as well, by leaving the type empty (the empty string).
+
+6. *read_incoming* similarly reads out all incoming associations of a certain type, for a specific element.
+   For example, to read out all incoming T2P links of a place::
+
+        >>> read_incoming("my_pn", "p2", "T2P")
+        ["t2p"]
+
+   Again, the type can be set to the empty string to return all incoming associations.
+
+7. *read_association_source* reads out the source of a specific association, and can be used in conjunction with *read_outgoing* and *read_incoming*.
+   For example, to read out which is the source of an arc::
+
+        >>> read_association_source("my_pn", "p2t")
+        p1
+
+8. *read_association_destination* similarly reads out the destination of a specific association.
+   For example, to read out the target of an arc::
+
+        >>> read_association_destination("my_pn", "p2t")
+        t1
+
+9. *connections_between* reads out the set of all association types that can be created between two elements in the model.
+   This also takes into account inheritance information.
+   For example, to find out which association types can connect a place and transition::
+
+        >>> connections_between("my_pn", "p1", "t1")
+        ["P2T"]
+
+    If no associations are allowed, the list is empty.
+
+10. *all_instances* read out the set of all instances of a specific type in the model.
+    For example, to find all Places in our PetriNet model::
+
+        >>> all_instances("my_pn", "Place")
+        ["p1", "p2"]
+
+Delete
+^^^^^^
+
+1. *delete_element* deletes the element from the model and the type mapping.
+   Note that currently, attribute values are not automatically removed from the model, and they will remain dangling.
+   Therefore, to prevent strange errors, it is safest to first delete all attributes of an element before deleting it.
+   Associations, however, are removed.
+   For example, to remove place p1::
+
+        >>> element_list_nice("my_pn")
+        [{"id": "p1", "type": "Place", "name": "place 1", "tokens": 1},
+         {"id": "p2", "type": "Place", "name": "place 2", "tokens": 2},
+         {"id": "t1", "type": "Transition"},
+         {"id": "p2t", "type": "P2T", "__source": "p1", "__target": "t1", "weight": 1},
+         {"id": "t2p", "type": "T2P", "__source": "t1", "__target": "p2", "weight": 2},
+        ]
+        >>> delete_element("my_pn", "p1")
+        >>> element_list_nice("my_pn")
+        [{"id": "p2", "type": "Place", "name": "place 2", "tokens": 2},
+         {"id": "t1", "type": "Transition"},
+         {"id": "t2p", "type": "T2P", "__source": "t1", "__target": "p2", "weight": 2},
+        ]
+
+2. *attr_delete* deletes an attribute from a model element.
+   The attribute is removed, basically rendering it undefined.
+   Nonetheless, if the attribute is optional, a subsequent *attr_assign* call is required to make sure that the model conforms.
+   Note that *attr_assign* automatically updates the attribute, so *attr_delete* is only necessary for optional attributes that must be unset.

+ 0 - 211
doc/mvc.rst

@@ -1,211 +0,0 @@
-Modelverse Core
-===============
-
-The Modelverse Core (MvC) is an example (meta-)modelling interface that can be used with a plethora of tools.
-While the MvC itself is rather simple and its interface is kind of hard to use, wrappers can be put in front of it to make the behaviour much friendlier.
-For example, a simple call to instantiate a specific class requires several XML/HTTPRequest calls back and forth.
-A simple wrapper can abstract from this complexity, while retaining the elegance of the versatile interface.
-
-The MvC at the moment is written for a simple textual interface, but can easily be augmented with additional information to make it more computer-readable.
-For example, requests and replies can make use of IDs to distinguish or identify the information being passed around, or perform context switches.
-
-The MvC manages the Modelverse information visible to all users.
-Since all information in the Modelverse is stored as a model, this user and model management information is stored as a model as well: the Core model.
-The core model is a mega-model that provides links to all other models stored in the Modelverse (including itself!).
-For each of these models, additional meta-information is stored within the Core model.
-Only admin users have read and write permission to the Core model by default: this model is used for all other operations.
-While some operations are allowed for other users, such as modifying the permissions of your own file, this write must be done with administrator permissions.
-Therefore, this MvC interface provides some specialized operations which check for the necessary permissions (*e.g.*, owner of the model), and then apply the requested operation with admin permissions.
-
-An overview of the MvC interface is shown below.
-A complete overview of the code is shown in the :download:`MvC core algorithm <../core/core_algorithm.alc>`
-None of these operations manipulate the model at a finer granularity: for that we use the :download:`Mini-Modify <../core/mini_modify.alc>` code, which is sometimes called.
-A detailed explanation of its operations is shown later.
-
-Model operations
-----------------
-
-The first set of operations are basic model management operations.
-
-model_add
-^^^^^^^^^
-
-Adds a new model to the Modelverse.
-Model content is specified using model constructors, which can be generated with the model compiler.
-
-model_modify
-^^^^^^^^^^^^
-
-Switches the interface to model-scope operations of a specific model.
-
-model_list
-^^^^^^^^^^
-
-Give an overview list of all models, showing their name and type.
-
-model_list_full
-^^^^^^^^^^^^^^^
-
-Give a detailed overview list of all models, showing their name, type, permissions, owner, and group.
-
-model_overwrite
-^^^^^^^^^^^^^^^
-
-Overwrite an existing model. Similar to *model_add*, but keeps existing meta-information to the model intact.
-
-verify
-^^^^^^
-
-Verify whether a model conforms to the specified metamodels.
-
-Transformation-specific operations
-----------------------------------
-
-The second set of operations are specific to model transformations.
-
-transformation_add_MT_language
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-Create a new RAMified metamodel out of several existing metamodels.
-The generated metamodel can be used to instantiate a model transformation.
-
-transformation_add_MT
-^^^^^^^^^^^^^^^^^^^^^
-
-Add a new model transformation schedule, including the rules.
-
-transformation_add_AL
-^^^^^^^^^^^^^^^^^^^^^
-
-Add a new action language model that operates on models.
-
-transformation_add_MANUAL
-^^^^^^^^^^^^^^^^^^^^^^^^^
-
-Add a new manual model transformation.
-
-transformation_execute
-^^^^^^^^^^^^^^^^^^^^^^
-
-Execute an existing transformation. Automatically finds out the type and executes the relevant interface.
-
-transformation_list
-^^^^^^^^^^^^^^^^^^^
-
-List known transformations and their type.
-
-transformation_list_full
-^^^^^^^^^^^^^^^^^^^^^^^^
-
-List known transformations and their type, as well as permissions, owner, and group.
-
-transformation_detail
-^^^^^^^^^^^^^^^^^^^^^
-
-Give details on a single transformation, such as the source and target formalisms.
-
-transformation_RAMify
-^^^^^^^^^^^^^^^^^^^^^
-
-RAMify an existing metamodel again.
-Useful if the related metamodel has changed.
-
-Process operations
-------------------
-
-The third set of operations is related to the execution and operation on an FTG+PM.
-
-process_execute
-^^^^^^^^^^^^^^^
-
-Execute an existing process model.
-
-Model permission operations
----------------------------
-
-The fourth set of operations is related to model access control management.
-
-permission_modify
-^^^^^^^^^^^^^^^^^
-
-Modifies the permission of a specified model.
-
-permission_owner
-^^^^^^^^^^^^^^^^
-
-Modifies the owner of a specified model.
-
-permission_group
-^^^^^^^^^^^^^^^^
-
-Modifies the group of a specified model.
-
-Group operations
-----------------
-
-The fifth set of operations is related to the management of groups.
-
-group_create
-^^^^^^^^^^^^
-
-Create a new group, and become its administrator.
-
-group_delete
-^^^^^^^^^^^^
-
-Delete a group for which you are administrator.
-
-group_owner_add
-^^^^^^^^^^^^^^^
-
-Add a new user as administrator to a group of which you are an administrator.
-
-group_owner_delete
-^^^^^^^^^^^^^^^^^^
-
-Remove a user as administrator from a group of which you are an administrator.
-
-group_join
-^^^^^^^^^^
-
-Add a new user to a group of which you are an administrator.
-
-group_kick
-^^^^^^^^^^
-
-Remove a user from a group of which you are an administrator.
-
-group_list
-^^^^^^^^^^
-
-List all known groups.
-
-Admin operations
-----------------
-
-The sixth set of operations is related to administrator operations.
-
-admin_promote
-^^^^^^^^^^^^^
-
-Promote another user as administrator as well.
-
-admin_demote
-^^^^^^^^^^^^
-
-Demote another user from administrator status.
-
-General operations
-------------------
-
-The final set of operations consists of miscellaneous operations.
-
-self-destruct
-^^^^^^^^^^^^^
-
-Destroy the current user, revoking all permissions of owning models.
-
-exit
-^^^^
-
-Exit the current task, while keeping the user intact.

+ 24 - 0
doc/operations.rst

@@ -0,0 +1,24 @@
+Operations
+==========
+
+Describe the different types of operations
+
+Model Transformations
+---------------------
+
+Link back to previous section
+
+Manual Operations
+-----------------
+
+Explain manual operations: do the merge and split automatically
+
+Action Language
+---------------
+
+Explain how to do things programmatically
+
+Process Model
+-------------
+
+Explain how process model can combine different operations and manage data flow as well as control flow

+ 138 - 0
doc/permissions.rst

@@ -0,0 +1,138 @@
+Permission system
+=================
+
+As the Modelverse runs as a service, and allows users to share models, permissions become required.
+We briefly introduce the permission system used in the Modelverse.
+
+As in the Modelverse everything is modelled explicitly, all permisions and meta-information about models is also modelled explicitly in the *core* model.
+This model is not readable to any user, but can be queried and altered through the provided set of operations.
+
+Model permissions
+-----------------
+
+First and foremost are the permissions on the models.
+When creating a new model with *model_add*, the model is by default only readable and writable for the creating user.
+All other users have neither read, nor write access unless explicitly granted by the creating user.
+Similar to UNIX permissions, we use numeric values to indicate permissions, in the form XYZ.
+X indicates the permissions of the owner itself.
+Y indicates the permissions of the owning group.
+Z indicates the permissions of all other users.
+
+The values can range from 0 to 2.
+0 indicates that the model is not readable, nor writable.
+1 indicates that the model is readable, but not writable.
+2 indicates that the model is both readable and writable.
+
+As such, a model can have permission 210.
+This indicates that the owner can read and write the model, the owning group can open the model read-only, and all other users have no access at all to the model.
+
+Models can be queried for their permission information with the *model_list_full* operation::
+
+    >>> model_list_full()
+    [("my_pn", "PetriNets", "user1", "group1", "200"),
+     ("my_pn2", "PetriNets", "user2", "group1", "210"),
+     ("my_pn3", "PetriNets", "user2", "group2", "210"),
+     ("my_pn4", "PetriNets", "user2", "group2", "211"),
+     ...
+    ]
+
+In this case, user1 can modify my_pn, as he is the owner (permission 2: read/write), read my_pn2, as he is a member of group1 (permission 1: read), and has no access to my_pn3, as he is neither owner, nor in the group (permission 0: none).
+All users can read my_pn4, independent of their group (permission 1: read).
+
+Permission management
+^^^^^^^^^^^^^^^^^^^^^
+
+To share your models, you basically need to relax their permissions.
+The default permissions are such that only the owning user can read/write the model, and no other users have access to it.
+To alter the permissions, we have access to several operations.
+
+1. *permission_modify* changes the permissions of a model to the specified string.
+   For example, to make my_pn readable for everyone::
+   
+    >>> permission_modify("my_pn", "211")
+
+2. *permission_owner* changes the owner of a model, thereby possibly revoking our own permission, but passing it on to someone else.
+   For example, to make user2 the owner of our PetriNet model::
+
+    >>> permission_owner("my_pn", "user2")
+
+3. *permission_group* changes the owning group of a model, thereby possibly revoking permissions for several users.
+   For example, to make group2 the owning group of our PetriNet model::
+
+    >>> permission_group("my_pn", "group2")
+
+Meta-level propagation
+^^^^^^^^^^^^^^^^^^^^^^
+
+Due to its meta-modelling nature, Modelverse permissions are more involved than just file-like permissions.
+Indeed, a model depends on the language used to create it, such as *PetriNets*.
+While in this case we have assumed *PetriNets* to be always readable, this does not necessarily need to be the case.
+
+Creating a new instance of an unreadable metamodel, or language, is of course impossible, and the call to *model_add* will be prevented.
+Worse, however, is when the permissions of the metamodel are altered when there already is a model in that language.
+In this case, the model will suddenly become unreadable, as it depends on an unreadable metamodel.
+Later on, we will see that this does not necessarily make it impossible for the model to be opened, as it only prevents it to be opened with that specific metamodel.
+This does, however, require multi-conformance, which is an advanced concepts that is currently out of scope of this tutorial.
+
+Group permissions
+-----------------
+
+Groups are merely sets of users.
+Users can be added to the group with the *group_join* operation.
+To make *user1* join *group1*::
+
+    >>> group_join("group1", "user1")
+
+Similarly, they can be removed from a group, thereby revoking all their permissions that were granted by the group.
+To make *user1* leave *group1* again::
+
+    >>> group_kick("group1", "user1")
+
+As groups are key to model permissions, care should be taken who is made a member of a specific group.
+Groups are themselves managed by group administrators, who govern the members of a specific group.
+Group administrators can create new group administrators as well, who also automatically become a member of the group.
+Similarly, group administrators can revoke the permissions of other group administrators::
+
+    >>> group_owner_add("group1", "user1")
+    >>> group_owner_delete("group1", "user1")
+
+Note that, when removing group administrator status of a user, the user will still be a member of the group, though no longer an administrator.
+As such, the result of the previous two commands will leave *user1* as a group member, even though that might not have been the case before.
+A *group_kick* automatically removes group administrator permissions as well.
+
+All users can create new groups, of which they automatically become the group administrator::
+    
+    >>> group_add("group2)
+
+Similarly, groups can be removed by the group owner.
+This not only removes the group, but also kicks all users and thereby revokes all permissions originally given by that group::
+
+    >>> group_delete("group2")
+
+User management
+---------------
+
+Users can manage the basics of their accounts.
+This includes changing their username.
+In this case, only the name is altered, and all permissions remain unaltered.
+This is because only the name changes, and not the internal representation of that user.
+For example, to change the username of *user1* to *user_1*::
+
+    >>> user_name("user1", "user_1")
+
+Similarly, users can alter their password::
+
+    >>> user_password("user_1", "new_password")
+
+In both cases, all currently active sessions remain active, but future logins need to use the new credentials.
+
+Administrators
+--------------
+
+Finally, there is still the notion of an administrator in the Modelverse.
+Administrators are basically like the root users on UNIX systems: independent of permissions, they are allowed to perform any operation they want.
+As such, they are implicitly owner of each model, administrator of all groups, and have full permissions for user management.
+The Modelverse is initialized with one administrator user, but administrators can create (promote) new administrators, or revoke their administrator permissions (demote)::
+
+    >>> admin_promote("user1")
+    >>> admin_demote("user1")

+ 26 - 0
doc/primitives.rst

@@ -0,0 +1,26 @@
+Functions
+=========
+
+Explain the different types of functions in the Modelverse.
+
+Primitive functions
+-------------------
+
+Explain primitive functions:
+hardcoded in kernel, no AL equivalent
+minimal set of functions to be ported for new kernel
+
+Compiled functions
+------------------
+
+Explain compiled functions:
+hardcoded in kernel, but AL equivalent
+can be ported for efficiency fo the resulting kernel, but not required
+
+Normal functions
+----------------
+
+Explain normal functions:
+completely in AL, no compiled equivalent
+can still be implemented by kernel as compiled for performance, though not required
+functions are likely to be flexible

+ 14 - 0
doc/problems.rst

@@ -1,2 +1,16 @@
 Common problems and solutions
 =============================
+
+List set of common problems and their solution
+
+TODO: body_id is None
+---------------------
+
+Missing definition after declaration
+
+TODO: None has no length
+------------------------
+
+Operations done on a failed object, such as a dictionary read on a non-existing element
+
+TODO: find more

+ 46 - 0
doc/process_enactment.rst

@@ -0,0 +1,46 @@
+Process Enactment
+=================
+
+A final operation that is useful to modellers, is the enactment of process models.
+When enacting a process model, a series of operations on models is automatically executed.
+
+Finding process models
+----------------------
+
+To find process models, you can easily query the Modelverse for models that conform to *ProcessModel*.
+All such models can be executed, given that the models and operations they refer to, exist.
+
+Enacting process models
+-----------------------
+
+To enact the process model, such as *query_state_space*, you must execute the following operation::
+
+    >>> process_execute("query_state_space", "my_", {})
+
+There are three parameters to this function, the first obviously being the name of the process model, as shown in *model_list*.
+The second parameter is a prefix for the models used in the process model.
+When executing a process model, data is processed and produced.
+By providing a prefix, the names of these models are first prefixed with the prefix, before they are resolved.
+As such, it becomes possible to execute a process in different contexts.
+
+.. note::
+   This behaviour is likely to change in the future, with the process taking a mapping from the terms in the process model, to actual names.
+
+The third parameter is a dictionary of callbacks.
+For each activity, it is possible for users to define a callback function.
+This function will be invoked when the specific activity is executed.
+For example, a manual operation will require user input, for which this callback function can then serve.
+In this case, lets assume that an activity in the process model, termed *refine_petrinet*, is a manual operation and requires user interaction.
+The call then becomes::
+
+    >>> def callback():
+    ...     # Any code required to create the Petrinet
+    ...     p = instantiate(None, "Place")
+    ...     t = instantiate(None, "Transition")
+    ...     instantiate(None, "P2T", (p, t))
+    ...     # Alternatively, we could have used raw_input() or so to prompt the user
+    ...
+    >>> process_execute("query_state_space", "my_", {"refine_petrinet": callback})
+
+When the process executes *refine_petrinet*, the callback function is executed, and the manual operation is terminated when the function terminates.
+Other types of operation, such as *model transformations* and *action language* can also have a callback function, but this is usually less important to end users and is therefore not elaborated on here.

doc/howto.rst → doc/scripts.rst


+ 19 - 0
doc/services.rst

@@ -0,0 +1,19 @@
+External Services
+=================
+
+Explain the use of services.
+
+Modelverse-side
+---------------
+
+Explain how services work in the Modelverse.
+
+Service-side
+------------
+
+Explain how services work in the Python wrapper.
+
+Example
+-------
+
+Give a full example of a service.

+ 75 - 0
doc/transformations.rst

@@ -0,0 +1,75 @@
+Model transformations
+=====================
+
+A next step in the Modelverse is the use of model transformations.
+Model transformations are implemented using RAMification, and are therefore also modelled explicitly.
+As such, all previous modelling concepts are again useful.
+
+Specification
+-------------
+
+To create a model transformation, users must specify a set of source metamodels and target metamodels.
+The model transformation will afterwards get a signature of these models.
+To create a simple Petri Net simulation transformation, we use the operation *transformation_add_MT* as follows::
+
+    >>> transformation_add_MT({"PN": "PetriNets"}, {"PN": "PetriNets"}, "pn_simulate", open("pn_simulate.mvc", "r").read())
+
+The first dictionary we pass, is the input dictionary: it specifies the name the model elements will get in the LHS, and the expected type of them.
+Similarly, the output dictionary specifies the name of output elements and their types.
+The actual metamodel in which the model transformation executes is defined as the merger of the keys in both the input and output dictionary.
+
+Note that in the transformation, all types are renamed by prepending the tag of their signature.
+For example, all types in the previous model transformation will be renamed by prepending *"PN/"* (e.g., *PN/Place*, *PN/P2T*).
+
+All types are renamed, in order to make multiple inputs with the same type possible.
+For example, when combining two models, both of the same type, but one of them being the *master*, it is possible to do the following::
+
+    >>> transformation_add_MT({"master": "PetriNets", "slave": "PetriNets"}, {"result": "PetriNets"}, "pn_merge", open("pn_merge.mvc", "r").read())
+
+In this case, the LHS can match specifically for elements of the master (e.g., *master/Place*).
+
+The output dictionary is interesting as well: multiple output models are possible, and these are based on the tags as well.
+When model elements do not match any tags, they are ignored.
+When a model element matches a tag, it is put into that specific output model.
+More information on tags can be found in the *invocation* subsection.
+
+We will now continue on how to specify a model transformation through modelling.
+
+RAMification
+^^^^^^^^^^^^
+
+Explain how RAMification works and what it does.
+Specifically, which attributes does it add etc.
+
+Rule specification
+^^^^^^^^^^^^^^^^^^
+
+How to specify a rule
+
+Schedule
+^^^^^^^^
+
+Scheduling constructs
+
+Invocation
+----------
+
+The actual binding is only done later on, upon invocation, and goes as follows::
+
+    >>> transformation_execute_MT("pn_simulate", {"PN": "my_pn"}, {"PN": "my_pn"})
+
+In this case, the model transformation takes the model *my_pn* as input for the *pn_simulate* model transformation, and writes out the result in *my_pn*.
+As the output model matches the input model, the model transformation is effectively in-place.
+For out-place transformations, it is possible to specify a different output model, in which case the model is implicitly copied as well::
+
+    >>> transformation_execute_MT("pn_simulate", {"PN": "my_pn"}, {"PN": "my_simulated_pn"})
+
+Model transformation invocation has no effect on the original model in this case.
+Also, model transformations always happen on a copy of the original model.
+As such, it is also possible to restore the model to before the transformation.
+When a model transformation fails (i.e., the schedule ends in a *Failure*), no output models are written and the models are left untouched.
+
+Tracability links
+-----------------
+
+How do tracability links work?

+ 31 - 0
doc/users.rst

@@ -0,0 +1,31 @@
+Types of users
+==============
+
+For the Modelverse, we identify three types of users.
+It is possible for users to switch between these three different types over time.
+The remainder of this documentation is split up based on these three types of users: modellers, language engineers, and developers.
+Due to the design of the Modelverse, language engineers must also know all about modelling: languages are created through modelling.
+Similarly, developers must know about all knowledge of the modeller and language engineer, as they must implement operations for them.
+Nonetheless, there is still a different focus and different requirements for their domain knowledge.
+
+Modeller
+--------
+
+The majority of the users of the Modelverse will fall in the category of modellers.
+These users make use of the languages provided by other users, by instantiating them.
+While this is likely the biggest category of users, they will mostly be abstracted from the Modelverse wrapper by their MvI.
+For modellers, the documentation is focused on instantiating existing languages and modifying models or executing processes on specific models.
+
+Language Engineer
+-----------------
+
+Language engineers are the second category of users, who create language to be used by the modellers.
+Language engineering in the Modelverse is similar to modelling, as metamodels are models themselves.
+
+Developer
+---------
+
+The final category of users is that of developer.
+Developers of the Modelverse will modify the internals of the Modelverse, but, as the Modelvers is explicitly modelled, this often takes the form of a modeller as well.
+Nonetheless, the various files are stored external to the Modelverse, and can be modified without the Modelverse.
+Similarly, some core languages are also included in the Modelverse, which requires developers to be familiar with language engineering.

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 1225 - 0
doc/wrappers.rst


+ 6 - 4
hybrid_server/classes/mvkcontroller.xml

@@ -2,6 +2,7 @@
     <relationships>
         <association name="to_mvi" class="Server" min="1" max="1"/>
         <association name="tasks" class="Task"/>
+        <association name="services" class="Service"/>
     </relationships>
     <constructor>
         <parameter name="params"/>
@@ -277,7 +278,8 @@
                                     first = self.mvs.read_edge(outgoing[0])
                                     dest = first[1]
                                     name = self.mvs.read_value(dest)
-                                    if name.startswith("__"):
+                                    if name == "__hierarchy":
+                                        # Skip the special case, as this is neither data, nor a task
                                         continue
                                     tasks.add(name)
 
@@ -288,7 +290,7 @@
 
                         <transition cond="self.new_tasks" target="../create_SC"/>
                         <transition cond="not self.new_tasks and self.old_tasks" target="../remove_SC"/>
-                        <transition after="1" target="."/>
+                        <transition after="1.0" target="."/>
                     </state>
 
                     <state id="create_SC" initial="creating">
@@ -298,8 +300,8 @@
                                     self.task = self.new_tasks.pop()
                                 </script>
                                 <raise event="create_instance" scope="cd">
-                                    <parameter expr="'tasks'"/>
-                                    <parameter expr="'Task'"/>
+                                    <parameter expr="'services' if self.task.startswith('__') else 'tasks'"/>
+                                    <parameter expr="'Service' if self.task.startswith('__') else 'Task'"/>
                                     <parameter expr="self.task"/>
                                     <parameter expr="self.mvs_operations"/>
                                     <parameter expr="self.mvk"/>

+ 123 - 0
hybrid_server/classes/service.xml

@@ -0,0 +1,123 @@
+<class name="Service">
+    <relationships>
+        <association name="parent" class="MvKController" min="1" max="1"/>
+    </relationships>
+    <constructor>
+        <parameter name="taskname"/>
+        <parameter name="mvs_operations"/>
+        <parameter name="mvk"/>
+        <body>
+            <![CDATA[
+            self.taskname = taskname
+            self.mvs_operations = mvs_operations
+            self.mvk = mvk
+
+            self.failed = False
+            self.output_queue = []
+            self.outputs = []
+            self.do_yield = False
+            ]]>
+        </body>
+
+    </constructor>
+
+    <method name="execute_modelverse">
+        <parameter name="taskname"/>
+        <parameter name="operation"/>
+        <parameter name="params"/>
+        <body>
+            <![CDATA[
+            reply = None
+            commands = []
+            mvk = self.mvk
+            mvs_operations = self.mvs_operations
+            try:
+                while 1:
+                    commands = mvk.execute_yields(taskname, operation, params, reply)
+                    if commands is None:
+                        break
+                    reply = [mvs_operations[command[0]](*(command[1])) for command in commands]
+            except:
+                import traceback
+                print(traceback.format_exc())
+                #TODO delete self, as the task has crashed!
+                return False
+            return True
+            ]]>
+        </body>
+    </method>
+
+    <scxml initial="start">
+        <parallel id="start">
+            <state id="execution" initial="running">
+                <state id="running" initial="executing">
+                    <state id="executing">
+                        <onentry>
+                            <script>
+                                self.do_yield = True
+                                while self.output_queue:
+                                    if self.execute_modelverse(self.taskname, "get_output", []):
+                                        if self.mvk.success:
+                                            self.outputs.append((self.output_queue.pop(0), self.mvk.returnvalue))
+                                        else:
+                                            # No output left in Mv, so break
+                                            break
+                                    else:
+                                        self.failed = True
+                                        break
+                            </script>
+                        </onentry>
+
+                        <transition cond="self.failed" target="../../failed"/>
+                        <transition cond="self.do_yield" target="../yielded"/>
+                    </state>
+
+                    <state id="yielded">
+                        <transition after="self.sccd_yield() + 0.2" target="../executing"/>
+                        <transition event="processed_input" target="../executing"/>
+                        <transition event="waiting_output" target="../executing"/>
+                    </state>
+                </state>
+
+                <state id="failed">
+                    <state id="failed">
+                        <!-- TODO delete task -->
+                    </state>
+                </state>
+            </state>
+
+            <state id="process_events">
+                <state id="process_events">
+                    <transition event="input" target=".">
+                        <parameter name="params"/>
+                        <script>
+                            for args_entry in params:
+                                if not self.execute_modelverse(self.taskname, "set_input", [args_entry]):
+                                    # Failed!
+                                    self.failed = True
+                                    break
+                        </script>
+                        <raise event="processed_input"/>
+                    </transition>
+
+                    <transition event="output" target=".">
+                        <parameter name="params"/>
+                        <script>
+                            self.output_queue.append(params)
+                        </script>
+                        <raise event="waiting_output"/>
+                    </transition>
+
+                    <transition cond="self.outputs" target=".">
+                        <script>
+                            source, value = self.outputs.pop(0)
+                        </script>
+                        <raise event="HTTP_input" scope="narrow" target="'parent/to_mvi/%s' % source">
+                            <parameter expr="json.dumps(value)"/>
+                        </raise>
+                    </transition>
+                </state>
+            </state>
+        </parallel>
+    </scxml>
+</class>

+ 117 - 78
hybrid_server/classes/task.xml

@@ -11,11 +11,11 @@
             self.taskname = taskname
             self.mvs_operations = mvs_operations
             self.mvk = mvk
+            self.unlocked = True
 
-            self.failed = False
+            self.input_queue = []
             self.output_queue = []
             self.outputs = []
-            self.do_yield = False
             ]]>
         </body>
 
@@ -37,90 +37,26 @@
                     if commands is None:
                         break
                     reply = [mvs_operations[command[0]](*(command[1])) for command in commands]
+                return (0.0, False)
+            except SleepKernel as e:
+                return (e.timeout, e.interruptable)
             except:
-                print("ERROR: " + str(self.mvk.debug_info.get(taskname, "Unknown taskname")))
-                #TODO delete self, as the task has crashed!
-                return False
-            return True
+                import traceback
+                print(traceback.format_exc())
+                return (float('inf'), False)
             ]]>
         </body>
     </method>
 
-    <scxml initial="start">
-        <parallel id="start">
-            <state id="execution" initial="running">
-                <state id="running" initial="executing">
-                    <transition event="pause_task" target="../suspended"/>
-
-                    <state id="executing">
-                        <onentry>
-                            <script>
-                                start_time = time.time()
-                                # Grant each task some milliseconds of execution
-                                self.do_yield = False
-                                while (time.time() - start_time &lt; 0.05):
-                                    if not self.execute_modelverse(self.taskname, "execute_rule", []):
-                                        # Failed!
-                                        self.failed = True
-                                        break
-
-                                    if not self.mvk.success:
-                                        # Blocking or broken, so quit already to stop wasting CPU
-                                        self.do_yield = True
-                                        break
-
-                                if not self.failed:
-                                    # Perform output if there is anything
-                                    while self.output_queue:
-                                        if self.execute_modelverse(self.taskname, "get_output", []):
-                                            if self.mvk.success:
-                                                self.outputs.append((self.output_queue.pop(0), self.mvk.returnvalue))
-                                            else:
-                                                # No output left in Mv, so break
-                                                break
-                                        else:
-                                            self.failed = True
-                                            break
-                            </script>
-                        </onentry>
-
-                        <transition cond="self.failed" target="../../failed"/>
-                        <transition after="self.sccd_yield()" target="."/>
-                        <transition cond="self.do_yield" target="../yielded"/>
-                    </state>
-
-                    <state id="yielded">
-                        <transition after="self.sccd_yield() + 1" target="../executing"/>
-                        <transition event="processed_input" target="../executing"/>
-                        <transition event="waiting_output" target="../executing"/>
-                    </state>
-                </state>
-
-                <state id="suspended">
-                    <state id="suspended">
-                        <transition event="resume" target="../../running"/>
-                    </state>
-                </state>
-
-                <state id="failed">
-                    <state id="failed">
-                        <!-- TODO delete task -->
-                    </state>
-                </state>
-            </state>
-
-            <state id="process_events">
-                <state id="process_events">
+    <scxml initial="main">
+        <parallel id="main">
+            <state id="queue">
+                <state id="queue">
                     <transition event="input" target=".">
                         <parameter name="params"/>
                         <script>
-                            for args_entry in params:
-                                if not self.execute_modelverse(self.taskname, "set_input", [args_entry]):
-                                    # Failed!
-                                    self.failed = True
-                                    break
+                            self.input_queue.extend(params)
                         </script>
-                        <raise event="processed_input"/>
                     </transition>
 
                     <transition event="output" target=".">
@@ -128,7 +64,6 @@
                         <script>
                             self.output_queue.append(params)
                         </script>
-                        <raise event="waiting_output"/>
                     </transition>
 
                     <transition cond="self.outputs" target=".">
@@ -141,6 +76,110 @@
                     </transition>
                 </state>
             </state>
+
+            <state id="process" initial="running">
+                <state id="running" initial="components">
+                    <transition event="suspend" target="../suspended"/>
+
+                    <history id="history" type="deep"/>
+
+                    <parallel id="components">
+                        <state id="input">
+                            <state id="input">
+                                <transition cond="self.input_queue" target=".">
+                                    <script>
+                                        for args_entry in self.input_queue:
+                                            self.execute_modelverse(self.taskname, "set_input", [args_entry])
+                                        self.input_queue = []
+                                    </script>
+                                    <raise event="wake_timer"/>
+                                </transition>
+                            </state>
+                        </state>
+
+                        <state id="processing" initial="processing">
+                            <state id="processing">
+                                <onentry>
+                                    <script>
+                                        start_time = time.time()
+                                        # Grant each task some milliseconds of execution
+                                        while (time.time() - start_time &lt; 0.05):
+                                            timeout = self.execute_modelverse(self.taskname, "execute_rule", [])
+                                            if timeout[0] > 0.0:
+                                                # We should not continue immediately
+                                                break
+                                        self.timeout = timeout
+                                    </script>
+                                </onentry>
+
+                                <transition cond="self.timeout[0] == 0.0" after="self.sccd_yield()" target="."/>
+                                <transition cond="0.0 &lt; self.timeout[0] &lt; float('inf')" after="self.sccd_yield()" target="../blocked">
+                                    <script>
+                                        self.unlocked = False
+                                    </script>
+                                    <raise event="start_timer">
+                                        <parameter expr="self.timeout[0]"/>
+                                        <parameter expr="self.timeout[1]"/>
+                                    </raise>
+                                </transition>
+                                <transition cond="self.timeout[0] == float('inf')" target="../failed"/>
+                            </state>
+
+                            <state id="blocked">
+                                <transition cond="self.unlocked" target="../processing"/>
+                            </state>
+
+                            <state id="failed">
+                                <script>
+                                    print("TODO: task has failed")
+                                </script>
+                            </state>
+                        </state>
+
+                        <state id="output">
+                            <state id="output">
+                                <onentry>
+                                    <script>
+                                        if self.output_queue:
+                                            if self.execute_modelverse(self.taskname, "get_output", []):
+                                                if self.mvk.success:
+                                                    self.outputs.append((self.output_queue.pop(0), self.mvk.returnvalue))
+                                    </script>
+                                </onentry>
+
+                                <transition after="self.sccd_yield() + 0.1" target="."/>
+                            </state>
+                        </state>
+                    </parallel>
+                </state>
+
+                <state id="suspended">
+                    <transition event="resume" target="../running/history"/>
+                </state>
+            </state>
+
+            <state id="timer" initial="ready">
+                <state id="waiting">
+                    <transition after="self.sccd_yield() + self.timer_duration" target="../ready"/>
+                    <transition event="wake_timer" cond="self.interruptable" target="../ready"/>
+                </state>
+
+                <state id="ready">
+                    <onentry>
+                        <script>
+                            self.unlocked = True
+                        </script>
+                    </onentry>
+                    <transition event="start_timer" target="../waiting">
+                        <parameter name="duration"/>
+                        <parameter name="interruptable"/>
+                        <script>
+                            self.timer_duration = duration
+                            self.interruptable = interruptable
+                        </script>
+                    </transition>
+                </state>
+            </state>
         </parallel>
     </scxml>
 </class>

+ 2 - 0
hybrid_server/server.xml

@@ -15,6 +15,7 @@
         from collections import defaultdict
         sys.path.append("../kernel/")
         sys.path.append("../state/")
+        from modelverse_kernel.primitives import SleepKernel
         from modelverse_kernel.main import ModelverseKernel
         from modelverse_kernel.legacy import ModelverseKernel as LegacyModelverseKernel
         from modelverse_state.main import ModelverseState
@@ -29,4 +30,5 @@
     <class src="classes/server.xml"/>
     <class src="classes/socket.xml"/>
     <class src="classes/task.xml"/>
+    <class src="classes/service.xml"/>
 </diagram>

+ 176 - 0
integration/code/minimal_SCCD.mvc

@@ -0,0 +1,176 @@
+include "primitives.alh"
+
+Diagram my_SCCD {
+    name = "SimpleSCCD"
+    author = "Yentl"
+}
+
+Class main {
+    name = "Main"
+    default = True
+    constructor_body = $
+            Void function const(attributes : Element, parameters : Element):
+                dict_overwrite(attributes, "a", 0)
+                if (element_eq(parameters, read_root())):
+                    dict_overwrite(attributes, "id", 0)
+                else:
+                    dict_overwrite(attributes, "id", parameters)
+                return !
+        $
+}
+
+Attribute attr_a {
+    name = "a"
+}
+
+Attribute attr_b {
+    name = "id"
+}
+
+class_attributes (main, attr_a) {}
+class_attributes (main, attr_b) {}
+
+CompositeState main_statechart {
+    name = "root"
+    isInitial = True
+    {composite_children} BasicState init {
+        name = "initial"
+        isInitial = True
+        onEntryScript = $
+            Void function entry(attributes : Element):
+                log("ENTRY initial")
+                return!
+            $
+    }
+
+    {composite_children} BasicState exit {
+        name = "exit"
+        isInitial = False
+        onEntryScript = $
+            Void function entry(attributes : Element):
+                log("ENTRY exit")
+                return!
+            $
+    }
+
+    {composite_children} ParallelState main_parallel {
+        name = "parallel"
+        isInitial = False
+
+        {parallel_children} CompositeState parallel_x {
+            {composite_children} BasicState x_a {
+                name = "xa"
+                isInitial = True
+                onEntryScript = $
+                        Void function entry(attributes : Element):
+                            log("ENTRY xa")
+                            return!
+                    $
+                onExitScript = $
+                        Void function exit(attributes : Element):
+                            log("EXIT xa")
+                            return!
+                    $
+            }
+            {composite_children} BasicState x_b {
+                name = "xb"
+                isInitial = False
+                onEntryScript = $
+                        Void function entry(attributes : Element):
+                            log("ENTRY xb")
+                            return!
+                    $
+                onExitScript = $
+                        Void function exit(attributes : Element):
+                            log("EXIT xb")
+                            return!
+                    $
+            }
+            {composite_children} BasicState x_c {
+                name = "xc"
+                isInitial = False
+            }
+            {composite_children} BasicState x_d {
+                name = "xd"
+                isInitial = False
+            }
+        }
+
+        {parallel_children} CompositeState parallel_y {
+            {composite_children} BasicState y_a {
+                name = "ya"
+                isInitial = True
+            }
+            {composite_children} BasicState y_b {
+                name = "yb"
+                isInitial = False
+            }
+        }
+    }
+}
+
+transition (x_a, x_b) {
+    name = "X"
+    event = "X"
+    script = $
+            Void function script(attributes : Element, evt_param : Element):
+                log("In script")
+                dict_overwrite(attributes, "a", 1)
+                dict_overwrite(attributes, "id", 2)
+                return!
+        $
+}
+
+transition (x_a, x_d) {
+    name = "timeout"
+    after = $
+            Float function after(attributes : Element):
+                log("In after")
+                return 3.0!
+        $
+}
+
+transition (x_b, x_c) {
+    name = "Z"
+    cond = $
+            Boolean function cond(attributes : Element, evt_param : Element):
+                log("In condition")
+                return integer_lt(attributes["a"], attributes["id"])!
+        $
+}
+
+transition transition_y (y_a, y_b) {
+    name = "Y"
+    event = "Y"
+}
+
+Raise create_new_class {
+    scope = "cd"
+    event = "create_instance"
+    parameter = $
+            Element function func(attributes : Element, parameters : Element):
+                Element result
+                log("Executing create_instance!")
+                result = create_node()
+                list_append(result, "Main")
+                list_append(result, attributes["id"])
+                dict_overwrite(attributes, "id", integer_addition(attributes["id"], 1))
+                list_append(result, attributes["id"])
+                return result!
+        $
+}
+
+transition_raises (transition_y, create_new_class) {}
+
+transition (init, main_parallel) {
+    name = "init"
+    event = "init"
+}
+
+transition (main_parallel, exit) {
+    name = "exit"
+    event = "exit"
+}
+
+diagram_classes (my_SCCD, main) {}
+behaviour (main, main_statechart) {}

+ 12 - 3
integration/code/pm_pn_reachability.mvc

@@ -28,12 +28,21 @@ Next (refinePN, reachability) {}
 Next (reachability, reachability_print) {}
 Next (reachability_print, finish) {}
 
-Produces (initializePN, pn) {}
+Produces (initializePN, pn) {
+    name = "PetriNet"
+}
 Consumes (refinePN, pn) {
+    name = "PetriNet"
+}
+Produces (refinePN, pn) {
+    name = "PetriNet"
 }
-Produces (refinePN, pn) {}
 Consumes (reachability, pn) {
+    name = "PetriNet"
+}
+Produces (reachability, reachability_graph) {
+    name = "ReachabilityGraph"
 }
-Produces (reachability, reachability_graph) {}
 Consumes (reachability_print, reachability_graph) {
+    name = "ReachabilityGraph"
 }

+ 1 - 7
integration/code/pn_simulate.alc

@@ -7,7 +7,6 @@ include "modelling.alh"
 
 Boolean function simulate(model : Element):
 	// Do a single simulation step
-	log("Start PN step!")
 
 	// Find enabled transitions
 	Element all_transitions
@@ -17,8 +16,6 @@ Boolean function simulate(model : Element):
 	Element in_arcs
 	String arc_under_study
 
-	log("Got types: " + set_to_string(dict_keys(model["metamodel"]["model"])))
-
 	all_transitions = allInstances(model, "PetriNet_Runtime/Transition")
 	enabled_transitions = create_node()
 
@@ -35,9 +32,7 @@ Boolean function simulate(model : Element):
 			Integer present_tokens
 			Integer required_tokens
 			required_tokens = read_attribute(model, arc_under_study, "weight")
-			log("Weight: " + cast_i2s(required_tokens))
 			present_tokens = read_attribute(model, reverseKeyLookup(model["model"], read_edge_src(model["model"][arc_under_study])), "tokens")
-			log("Tokens: " + cast_i2s(present_tokens))
 			if (present_tokens < required_tokens):
 				// Less tokens than required, so disable the transition completely
 				enabled = False
@@ -48,7 +43,7 @@ Boolean function simulate(model : Element):
 	// Pick random enabled transition
 	String transition
 
-	transition = random_choice(enabled_transitions)
+	transition = random_choice(set_to_list(enabled_transitions))
 
 	// Consume tokens
 	Element workset
@@ -72,5 +67,4 @@ Boolean function simulate(model : Element):
 		instantiate_attribute(model, working_place, "tokens", new_value)
 
 	// Finish up
-	log("Finished PN Step!")
 	return True!

+ 2 - 2
integration/code/reachabilitygraph_print.mvc

@@ -19,9 +19,9 @@ Composite schedule {
                         Element dict_values
                         Element all_values
                         String place
-                        dict_values = create_node()
+                        dict_values = dict_create()
                         all_values = allAssociationDestinations(model, name, "ReachabilityGraph/Contains")
-                        while (read_nr_out(all_values) > 0):
+                        while (set_len(all_values) > 0):
                             place = set_pop(all_values)
                             dict_add(dict_values, read_attribute(model, place, "name"), read_attribute(model, place, "tokens"))
                         log((cast_v2s(read_attribute(model, name, "name")) + ": ") + dict_to_string(dict_values))

+ 12 - 0
integration/code/simple_client.alc

@@ -0,0 +1,12 @@
+include "primitives.alh"
+include "services.alh"
+
+Boolean function main(param : Element):
+	String port
+	port = comm_connect("fibonacci")
+	comm_set(port, 1)
+
+	Integer result
+	result = comm_get(port)
+	comm_close(port)
+	return True!

+ 118 - 88
integration/test_mvc.py

@@ -12,7 +12,21 @@ expected_model_list = set([("SimpleClassDiagrams", "SimpleClassDiagrams"),
                            ("ActionLanguage", "SimpleClassDiagrams"),
                            ("ProcessModel", "SimpleClassDiagrams"),
                            ("Tracability", "SimpleClassDiagrams"),
-                           ("core", "CoreFormalism")])
+                           ("conformance_mv", "ActionLanguage"),
+                           ("bottom", "SimpleClassDiagrams"),
+                           ("core", "CoreFormalism"),
+                           ('TypeMapping', 'SimpleClassDiagrams'),
+                           ('TM_SimpleClassDiagrams', 'TypeMapping'),
+                           ('TM_TypeMapping', 'TypeMapping'),
+                           ('TM_Tracability', 'TypeMapping'),
+                           ('TM_ProcessModel', 'TypeMapping'),
+                           ('TM_ActionLanguage', 'TypeMapping'),
+                           ('TM_ManualOperation', 'TypeMapping'),
+                           ('TM_conformance_mv', 'TypeMapping'),
+                           ('TM_CoreFormalism', 'TypeMapping'),
+                           ('TM_core', 'TypeMapping'),
+                           ('TM_bottom', 'TypeMapping'),
+                          ])
 
 expected_model_full_list = set([("SimpleClassDiagrams", "SimpleClassDiagrams", "admin", "admin", "221"),
                                 ("CoreFormalism", "SimpleClassDiagrams", "admin", "admin", "221"),
@@ -20,7 +34,23 @@ expected_model_full_list = set([("SimpleClassDiagrams", "SimpleClassDiagrams", "
                                 ("ActionLanguage", "SimpleClassDiagrams", "admin", "admin", "221"),
                                 ("ProcessModel", "SimpleClassDiagrams", "admin", "admin", "221"),
                                 ("Tracability", "SimpleClassDiagrams", "admin", "admin", "221"),
-                                ("core", "CoreFormalism", "admin", "admin", "200")])
+                                ("bottom", "SimpleClassDiagrams", "admin", "admin", "221"),
+                                ("conformance_mv", "ActionLanguage", "admin", "admin", "221"),
+                                ("core", "CoreFormalism", "admin", "admin", "220"),
+                                ('TypeMapping', 'SimpleClassDiagrams', "admin", "admin", "221"),
+                                ('TM_SimpleClassDiagrams', 'TypeMapping', "admin", "admin", "221"),
+                                ('TM_TypeMapping', 'TypeMapping', "admin", "admin", "221"),
+                                ('TM_Tracability', 'TypeMapping', "admin", "admin", "221"),
+                                ('TM_ProcessModel', 'TypeMapping', "admin", "admin", "221"),
+                                ('TM_ActionLanguage', 'TypeMapping', "admin", "admin", "221"),
+                                ('TM_ManualOperation', 'TypeMapping', "admin", "admin", "221"),
+                                ('TM_conformance_mv', 'TypeMapping', "admin", "admin", "221"),
+                                ('TM_CoreFormalism', 'TypeMapping', "admin", "admin", "221"),
+                                ('TM_core', 'TypeMapping', "admin", "admin", "220"),
+                                ('TM_bottom', 'TypeMapping', "admin", "admin", "221"),
+                                ])
+
+expected_transformation_list = set([("ActionLanguage", "conformance_mv")])
 
 class TestModelverseCore(unittest.TestCase):
     def setUp(self):
@@ -29,7 +59,10 @@ class TestModelverseCore(unittest.TestCase):
         login("admin", "admin")
 
     def tearDown(self):
-        kill(self.proc)
+        try:
+            kill(self.proc)
+        except:
+            print("Got exception during teardown.")
 
     def test_list(self):
         assert model_list() == expected_model_list
@@ -39,54 +72,49 @@ class TestModelverseCore(unittest.TestCase):
 
     def test_model_add_empty(self):
         model_add("Empty", "SimpleClassDiagrams")
-        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams")])
-        assert model_list_full() == set(list(expected_model_full_list) + [("Empty", "SimpleClassDiagrams", "admin", "nobody", "200")])
+        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams"), ("TM_Empty", "TypeMapping")])
+        assert model_list_full() == set(list(expected_model_full_list) + [("Empty", "SimpleClassDiagrams", "admin", "nobody", "200"),
+                                                                          ("TM_Empty", "TypeMapping", "admin", "nobody", "200"),
+                                                                         ])
+
+    def test_model_verify(self):
+        assert verify("SimpleClassDiagrams", "SimpleClassDiagrams") == "OK"
 
     def test_model_empty_instantiate(self):
         model_add("Empty", "SimpleClassDiagrams")
-        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams")])
-        assert model_list_full() == set(list(expected_model_full_list) + [("Empty", "SimpleClassDiagrams", "admin", "nobody", "200")])
+        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams"), ("TM_Empty", "TypeMapping")])
         assert element_list("Empty") == set([])
         instantiate("Empty", "Class", ID="A")
         assert element_list("Empty") == set([("A", "Class")])
-        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams")])
-        assert model_list_full() == set(list(expected_model_full_list) + [("Empty", "SimpleClassDiagrams", "admin", "nobody", "200")])
+        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams"), ("TM_Empty", "TypeMapping")])
 
     def test_model_overwrite(self):
         model_add("Empty", "SimpleClassDiagrams")
-        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams")])
-        assert model_list_full() == set(list(expected_model_full_list) + [("Empty", "SimpleClassDiagrams", "admin", "nobody", "200")])
+        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams"), ("TM_Empty", "TypeMapping")])
         assert element_list("Empty") == set([])
         instantiate("Empty", "Class", ID="A")
         assert element_list("Empty") == set([("A", "Class")])
         model_overwrite("Empty")
         assert element_list("Empty") == set([])
-        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams")])
-        assert model_list_full() == set(list(expected_model_full_list) + [("Empty", "SimpleClassDiagrams", "admin", "nobody", "200")])
+        assert model_list() == set(list(expected_model_list) + [("Empty", "SimpleClassDiagrams"), ("TM_Empty", "TypeMapping")])
         instantiate("Empty", "Class", ID="B")
         assert element_list("Empty") == set([("B", "Class")])
 
-    def test_transform_add_MT_language(self):
-        model_add("PetriNet", "SimpleClassDiagrams", open("integration/code/petrinets.mvc", "r").read())
-        assert model_list() == set(list(expected_model_list) + [("PetriNet", "SimpleClassDiagrams")])
-        transformation_add_MT_language(["PetriNet"], "PetriNet_RAM")
-        assert model_list() == set(list(expected_model_list) + [("PetriNet", "SimpleClassDiagrams"),
-                                                                ("PetriNet_RAM", "SimpleClassDiagrams"),
-                                                                ("__merged_PetriNet_RAM", "SimpleClassDiagrams")])
-
-    def test_transform_add_MT_instance(self):
+    def test_transform_add_MT(self):
         model_add("PetriNet", "SimpleClassDiagrams", open("integration/code/petrinets.mvc", "r").read())
-        assert model_list() == set(list(expected_model_list) + [("PetriNet", "SimpleClassDiagrams")])
-        transformation_add_MT_language(["PetriNet"], "PetriNet_RAM")
         assert model_list() == set(list(expected_model_list) + [("PetriNet", "SimpleClassDiagrams"),
-                                                                ("PetriNet_RAM", "SimpleClassDiagrams"),
-                                                                ("__merged_PetriNet_RAM", "SimpleClassDiagrams")])
-        transformation_add_MT("PetriNet_RAM", ["PetriNet"], [], "print_pn", open("integration/code/pn_print.mvc").read())
+                                                                ("TM_PetriNet", "TypeMapping"),
+                                                               ])
+        transformation_add_MT({"PetriNet": "PetriNet"}, {}, "print_pn", open("integration/code/pn_print.mvc").read())
         assert model_list() == set(list(expected_model_list) + [("PetriNet", "SimpleClassDiagrams"),
-                                                                ("PetriNet_RAM", "SimpleClassDiagrams"),
-                                                                ("__merged_PetriNet_RAM", "SimpleClassDiagrams"),
-                                                                ("print_pn", "PetriNet_RAM")])
-        assert transformation_list() == set([("ModelTransformation", "print_pn")])
+                                                                ("TM_PetriNet", "TypeMapping"),
+                                                                ("__RAM_print_pn", "SimpleClassDiagrams"),
+                                                                ("TM___RAM_print_pn", "TypeMapping"),
+                                                                ("__merged_print_pn", "SimpleClassDiagrams"),
+                                                                ("TM___merged_print_pn", "TypeMapping"),
+                                                                ("print_pn", "__RAM_print_pn"),
+                                                                ("TM_print_pn", "TypeMapping")])
+        assert transformation_list() == set(list(expected_transformation_list) + [("ModelTransformation", "print_pn")])
 
     def test_transform_add_MT_pn_print_exec(self):
         log = []
@@ -97,19 +125,22 @@ class TestModelverseCore(unittest.TestCase):
         model_add("PetriNet", "SimpleClassDiagrams", open("integration/code/pn_runtime.mvc", "r").read())
         model_add("my_pn", "PetriNet", open("integration/code/pn_runtime_model.mvc", "r").read())
         assert model_list() == set(list(expected_model_list) + [("PetriNet", "SimpleClassDiagrams"),
-                                                                ("my_pn", "PetriNet")])
-        transformation_add_MT_language(["PetriNet"], "PetriNet_RAM")
-        assert model_list() == set(list(expected_model_list) + [("PetriNet", "SimpleClassDiagrams"),
+                                                                ("TM_PetriNet", "TypeMapping"),
                                                                 ("my_pn", "PetriNet"),
-                                                                ("PetriNet_RAM", "SimpleClassDiagrams"),
-                                                                ("__merged_PetriNet_RAM", "SimpleClassDiagrams")])
-        transformation_add_MT("PetriNet_RAM", ["PetriNet"], [], "print_pn", open("integration/code/pn_print.mvc").read())
+                                                                ("TM_my_pn", "TypeMapping"),
+                                                               ])
+        transformation_add_MT({"PetriNet": "PetriNet"}, {}, "print_pn", open("integration/code/pn_print.mvc").read())
         assert model_list() == set(list(expected_model_list) + [("PetriNet", "SimpleClassDiagrams"),
+                                                                ("TM_PetriNet", "TypeMapping"),
                                                                 ("my_pn", "PetriNet"),
-                                                                ("PetriNet_RAM", "SimpleClassDiagrams"),
-                                                                ("__merged_PetriNet_RAM", "SimpleClassDiagrams"),
-                                                                ("print_pn", "PetriNet_RAM")])
-        assert transformation_list() == set([("ModelTransformation", "print_pn")])
+                                                                ("TM_my_pn", "TypeMapping"),
+                                                                ("__RAM_print_pn", "SimpleClassDiagrams"),
+                                                                ("TM___RAM_print_pn", "TypeMapping"),
+                                                                ("__merged_print_pn", "SimpleClassDiagrams"),
+                                                                ("TM___merged_print_pn", "TypeMapping"),
+                                                                ("print_pn", "__RAM_print_pn"),
+                                                                ("TM_print_pn", "TypeMapping")])
+        assert transformation_list() == set(list(expected_transformation_list) + [("ModelTransformation", "print_pn")])
         assert transformation_execute_MT("print_pn", {"PetriNet": "my_pn"}, {}, callback) == True
 
         assert set(log) == set(['"p1" --> 1',
@@ -140,17 +171,18 @@ class TestModelverseCore(unittest.TestCase):
 
         model_add("my_pn", "PetriNet", open("integration/code/pn_design_model.mvc", "r").read())
 
-        transformation_add_MT_language(["PetriNet", "PetriNet_Runtime"], "PetriNet_RAM")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet/Place", "PetriNet_Runtime/Place"), ID="D2R_PlaceLink")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet/Transition", "PetriNet_Runtime/Transition"), ID="D2R_TransitionLink")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet_Runtime/Place", "PetriNet/Place"), ID="R2D_PlaceLink")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet_Runtime/Transition", "PetriNet/Transition"), ID="R2D_TransitionLink")
-        transformation_RAMify("__merged_PetriNet_RAM", "PetriNet_RAM")
+        def add_tracability_D2R():
+            instantiate(None, "Association", ("PetriNet/Place", "PetriNet_Runtime/Place"), ID="D2R_PlaceLink")
+            instantiate(None, "Association", ("PetriNet/Transition", "PetriNet_Runtime/Transition"), ID="D2R_TransitionLink")
+
+        def add_tracability_R2D():
+            instantiate(None, "Association", ("PetriNet_Runtime/Place", "PetriNet/Place"), ID="R2D_PlaceLink")
+            instantiate(None, "Association", ("PetriNet_Runtime/Transition", "PetriNet/Transition"), ID="R2D_TransitionLink")
 
-        transformation_add_MT("PetriNet_RAM", ["PetriNet"], [], "print_pn", open("integration/code/pn_print.mvc").read())
-        transformation_add_MT("PetriNet_RAM", ["PetriNet"], ["PetriNet_Runtime"], "pn_design_to_runtime", open("integration/code/pn_design_to_runtime.mvc").read())
-        transformation_add_MT("PetriNet_RAM", ["PetriNet_Runtime"], ["PetriNet_Runtime"], "pn_simulate", open("integration/code/pn_simulate.mvc").read())
-        transformation_add_MT("PetriNet_RAM", ["PetriNet_Runtime"], ["PetriNet"], "pn_runtime_to_design", open("integration/code/pn_runtime_to_design.mvc").read())
+        transformation_add_MT({"PetriNet": "PetriNet"}, {}, "print_pn", open("integration/code/pn_print.mvc").read())
+        transformation_add_MT({"PetriNet": "PetriNet"}, {"PetriNet_Runtime": "PetriNet_Runtime"}, "pn_design_to_runtime", open("integration/code/pn_design_to_runtime.mvc").read(), add_tracability_D2R)
+        transformation_add_MT({"PetriNet_Runtime": "PetriNet_Runtime"}, {"PetriNet_Runtime": "PetriNet_Runtime"}, "pn_simulate", open("integration/code/pn_simulate.mvc").read())
+        transformation_add_MT({"PetriNet_Runtime": "PetriNet_Runtime"}, {"PetriNet": "PetriNet"}, "pn_runtime_to_design", open("integration/code/pn_runtime_to_design.mvc").read(), add_tracability_R2D)
 
         log = []
         assert transformation_execute_MT("print_pn", {"PetriNet": "my_pn"}, {}, callback) == True
@@ -179,17 +211,18 @@ class TestModelverseCore(unittest.TestCase):
 
         model_add("my_pn", "PetriNet", open("integration/code/pn_design_model.mvc", "r").read())
 
-        transformation_add_MT_language(["PetriNet", "PetriNet_Runtime"], "PetriNet_RAM")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet/Place", "PetriNet_Runtime/Place"), ID="D2R_PlaceLink")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet/Transition", "PetriNet_Runtime/Transition"), ID="D2R_TransitionLink")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet_Runtime/Place", "PetriNet/Place"), ID="R2D_PlaceLink")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet_Runtime/Transition", "PetriNet/Transition"), ID="R2D_TransitionLink")
-        transformation_RAMify("__merged_PetriNet_RAM", "PetriNet_RAM")
+        def add_tracability_D2R():
+            instantiate(None, "Association", ("PetriNet/Place", "PetriNet_Runtime/Place"), ID="D2R_PlaceLink")
+            instantiate(None, "Association", ("PetriNet/Transition", "PetriNet_Runtime/Transition"), ID="D2R_TransitionLink")
 
-        transformation_add_MT("PetriNet_RAM", ["PetriNet"], [], "print_pn", open("integration/code/pn_print.mvc").read())
-        transformation_add_MT("PetriNet_RAM", ["PetriNet"], ["PetriNet_Runtime"], "pn_design_to_runtime", open("integration/code/pn_design_to_runtime.mvc").read())
-        transformation_add_AL(["PetriNet_Runtime"], ["PetriNet_Runtime"], "pn_simulate", open("integration/code/pn_simulate.alc").read())
-        transformation_add_MT("PetriNet_RAM", ["PetriNet_Runtime"], ["PetriNet"], "pn_runtime_to_design", open("integration/code/pn_runtime_to_design.mvc").read())
+        def add_tracability_R2D():
+            instantiate(None, "Association", ("PetriNet_Runtime/Place", "PetriNet/Place"), ID="R2D_PlaceLink")
+            instantiate(None, "Association", ("PetriNet_Runtime/Transition", "PetriNet/Transition"), ID="R2D_TransitionLink")
+
+        transformation_add_MT({"PetriNet": "PetriNet"}, {}, "print_pn", open("integration/code/pn_print.mvc").read())
+        transformation_add_MT({"PetriNet": "PetriNet"}, {"PetriNet_Runtime": "PetriNet_Runtime"}, "pn_design_to_runtime", open("integration/code/pn_design_to_runtime.mvc").read(), add_tracability_D2R)
+        transformation_add_AL({"PetriNet_Runtime": "PetriNet_Runtime"}, {"PetriNet_Runtime": "PetriNet_Runtime"}, "pn_simulate", open("integration/code/pn_simulate.alc").read())
+        transformation_add_MT({"PetriNet_Runtime": "PetriNet_Runtime"}, {"PetriNet": "PetriNet"}, "pn_runtime_to_design", open("integration/code/pn_runtime_to_design.mvc").read(), add_tracability_R2D)
 
         log = []
         assert transformation_execute_MT("print_pn", {"PetriNet": "my_pn"}, {}, callback) == True
@@ -238,17 +271,18 @@ class TestModelverseCore(unittest.TestCase):
 
         model_add("my_pn", "PetriNet", open("integration/code/pn_design_model.mvc", "r").read())
 
-        transformation_add_MT_language(["PetriNet", "PetriNet_Runtime"], "PetriNet_RAM")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet/Place", "PetriNet_Runtime/Place"), ID="D2R_PlaceLink")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet/Transition", "PetriNet_Runtime/Transition"), ID="D2R_TransitionLink")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet_Runtime/Place", "PetriNet/Place"), ID="R2D_PlaceLink")
-        instantiate("__merged_PetriNet_RAM", "Association", ("PetriNet_Runtime/Transition", "PetriNet/Transition"), ID="R2D_TransitionLink")
-        transformation_RAMify("__merged_PetriNet_RAM", "PetriNet_RAM")
+        def add_tracability_D2R():
+            instantiate(None, "Association", ("PetriNet/Place", "PetriNet_Runtime/Place"), ID="D2R_PlaceLink")
+            instantiate(None, "Association", ("PetriNet/Transition", "PetriNet_Runtime/Transition"), ID="D2R_TransitionLink")
+
+        def add_tracability_R2D():
+            instantiate(None, "Association", ("PetriNet_Runtime/Place", "PetriNet/Place"), ID="R2D_PlaceLink")
+            instantiate(None, "Association", ("PetriNet_Runtime/Transition", "PetriNet/Transition"), ID="R2D_TransitionLink")
 
-        transformation_add_MT("PetriNet_RAM", ["PetriNet"], [], "print_pn", open("integration/code/pn_print.mvc").read())
-        transformation_add_MANUAL(["PetriNet"], ["PetriNet_Runtime"], "pn_design_to_runtime")
-        transformation_add_AL(["PetriNet_Runtime"], ["PetriNet_Runtime"], "pn_simulate", open("integration/code/pn_simulate.alc").read())
-        transformation_add_MT("PetriNet_RAM", ["PetriNet_Runtime"], ["PetriNet"], "pn_runtime_to_design", open("integration/code/pn_runtime_to_design.mvc").read())
+        transformation_add_MT({"PetriNet": "PetriNet"}, {}, "print_pn", open("integration/code/pn_print.mvc").read())
+        transformation_add_MANUAL({"PetriNet": "PetriNet"}, {"PetriNet_Runtime": "PetriNet_Runtime"}, "pn_design_to_runtime", add_tracability_D2R)
+        transformation_add_AL({"PetriNet_Runtime": "PetriNet_Runtime"}, {"PetriNet_Runtime": "PetriNet_Runtime"}, "pn_simulate", open("integration/code/pn_simulate.alc").read())
+        transformation_add_MT({"PetriNet_Runtime": "PetriNet_Runtime"}, {"PetriNet": "PetriNet"}, "pn_runtime_to_design", open("integration/code/pn_runtime_to_design.mvc").read(), add_tracability_R2D)
 
         log = []
         assert transformation_execute_MT("print_pn", {"PetriNet": "my_pn"}, {}, callback) == True
@@ -270,12 +304,10 @@ class TestModelverseCore(unittest.TestCase):
         model_add("PetriNet", "SimpleClassDiagrams", open("integration/code/pn_design.mvc", "r").read())
         model_add("ReachabilityGraph", "SimpleClassDiagrams", open("integration/code/reachability_graph.mvc", "r").read())
         model_add("pn_reachability", "ProcessModel", open("integration/code/pm_pn_reachability.mvc", "r").read())
-        transformation_add_MT_language(["PetriNet"], "PetriNet_RAM")
-        transformation_add_MT_language(["ReachabilityGraph"], "ReachabilityGraph_RAM")
-        transformation_add_MT("PetriNet_RAM", [], ["PetriNet"], "initialize_PN", open("integration/code/initialize_PN.mvc", "r").read())
-        transformation_add_MANUAL(["PetriNet"], ["PetriNet"], "refine_PN")
-        transformation_add_AL(["PetriNet"], ["ReachabilityGraph"], "reachability", open("integration/code/reachability.alc", "r").read())
-        transformation_add_MT("ReachabilityGraph_RAM", ["ReachabilityGraph"], [], "reachability_print", open("integration/code/reachabilitygraph_print.mvc", 'r').read())
+        transformation_add_MT({}, {"PetriNet": "PetriNet"}, "initialize_PN", open("integration/code/initialize_PN.mvc", "r").read())
+        transformation_add_MANUAL({"PetriNet": "PetriNet"}, {"PetriNet": "PetriNet"}, "refine_PN")
+        transformation_add_AL({"PetriNet": "PetriNet"}, {"ReachabilityGraph": "ReachabilityGraph"}, "reachability", open("integration/code/reachability.alc", "r").read())
+        transformation_add_MT({"ReachabilityGraph": "ReachabilityGraph"}, {}, "reachability_print", open("integration/code/reachabilitygraph_print.mvc", 'r').read())
 
         def callback_refine_PN():
             p1 = instantiate(None, "PetriNet/Place")
@@ -302,12 +334,10 @@ class TestModelverseCore(unittest.TestCase):
         model_add("PetriNet", "SimpleClassDiagrams", open("integration/code/pn_design.mvc", "r").read())
         model_add("ReachabilityGraph", "SimpleClassDiagrams", open("integration/code/reachability_graph.mvc", "r").read())
         model_add("pn_reachability", "ProcessModel", open("integration/code/pm_pn_reachability.mvc", "r").read())
-        transformation_add_MT_language(["PetriNet"], "PetriNet_RAM")
-        transformation_add_MT_language(["ReachabilityGraph"], "ReachabilityGraph_RAM")
-        transformation_add_MT("PetriNet_RAM", [], ["PetriNet"], "initialize_PN", open("integration/code/initialize_PN.mvc", "r").read())
-        transformation_add_MANUAL(["PetriNet"], ["PetriNet"], "refine_PN")
-        transformation_add_AL(["PetriNet"], ["ReachabilityGraph"], "reachability", open("integration/code/reachability_subfunction.alc", "r").read())
-        transformation_add_MT("ReachabilityGraph_RAM", ["ReachabilityGraph"], [], "reachability_print", open("integration/code/reachabilitygraph_print.mvc", 'r').read())
+        transformation_add_MT({}, {"PetriNet": "PetriNet"}, "initialize_PN", open("integration/code/initialize_PN.mvc", "r").read())
+        transformation_add_MANUAL({"PetriNet": "PetriNet"}, {"PetriNet": "PetriNet"}, "refine_PN")
+        transformation_add_AL({"PetriNet": "PetriNet"}, {"ReachabilityGraph": "ReachabilityGraph"}, "reachability", open("integration/code/reachability_subfunction.alc", "r").read())
+        transformation_add_MT({"ReachabilityGraph": "ReachabilityGraph"}, {}, "reachability_print", open("integration/code/reachabilitygraph_print.mvc", 'r').read())
 
         def callback_refine_PN():
             p1 = instantiate(None, "PetriNet/Place")
@@ -335,9 +365,9 @@ class TestModelverseCore(unittest.TestCase):
         model_add("MM_rendered_graphical", "SimpleClassDiagrams", open("models/MM_rendered_graphical.mvc", 'r').read())
         model_add("my_CBD", "CausalBlockDiagrams", open("integration/code/my_cbd.mvc", 'r').read())
 
-        transformation_add_MT_language(["CausalBlockDiagrams", "MM_rendered_graphical"], "CBD_RAM")
-        instantiate("__merged_CBD_RAM", "Association", ("CausalBlockDiagrams/Block", "MM_rendered_graphical/Group"), ID="TracabilityLink")
-        transformation_RAMify("__merged_CBD_RAM", "CBD_RAM")
+        def add_tracability():
+            instantiate(None, "Association", ("abstract/Block", "rendered/Group"), ID="TracabilityLink")
 
-        transformation_add_MT("CBD_RAM", ["CausalBlockDiagrams", "MM_rendered_graphical"], ["MM_rendered_graphical"], "render_graphical_CBD", open("models/CBD_mapper.mvc", 'r').read())
-        model_render("my_CBD", "render_graphical_CBD")
+        transformation_add_MT({"abstract": "CausalBlockDiagrams", "rendered": "MM_rendered_graphical"}, {"abstract": "CausalBlockDiagrams", "rendered": "MM_rendered_graphical"}, "render_graphical_CBD", open("models/CBD_mapper.mvc", 'r').read(), add_tracability)
+        result = model_render("my_CBD", "render_graphical_CBD")
+        assert len(result) == 23

+ 131 - 58
integration/test_powerwindow.py

@@ -41,45 +41,76 @@ class TestPowerWindow(unittest.TestCase):
                 ("Architecture", "SimpleClassDiagrams"),
                 ("pm_powerwindow", "ProcessModel"),
                 ("SimpleClassDiagrams", "SimpleClassDiagrams"),
+                ("TypeMapping", "SimpleClassDiagrams"),
                 ("CoreFormalism", "SimpleClassDiagrams"),
                 ("ManualOperation", "SimpleClassDiagrams"),
+                ("bottom", "SimpleClassDiagrams"),
                 ("ActionLanguage", "SimpleClassDiagrams"),
                 ("ProcessModel", "SimpleClassDiagrams"),
                 ("Tracability", "SimpleClassDiagrams"),
-                ("core", "CoreFormalism"),])
-
-        transformation_add_MT_language(["PetriNet", "Encapsulated_PetriNet", "PW_Plant", "PW_Control", "PW_Environment", "Requirements", "ReachabilityGraph", "Query", "Architecture"], "All_RAM")
-        instantiate("__merged_All_RAM", "Association", ("PW_Control/State", "Encapsulated_PetriNet/Place"), ID="CTRL2EPN_link")
-        instantiate("__merged_All_RAM", "Association", ("PW_Control/Transition", "Encapsulated_PetriNet/Transition"), ID="CTRL2EPN_tlink")
-        instantiate("__merged_All_RAM", "Association", ("PW_Plant/State", "Encapsulated_PetriNet/Place"), ID="PLANT2EPN_link")
-        instantiate("__merged_All_RAM", "Association", ("PW_Plant/Transition", "Encapsulated_PetriNet/Transition"), ID="PLANT2EPN_tlink")
-        instantiate("__merged_All_RAM", "Association", ("PW_Environment/Event", "Encapsulated_PetriNet/Place"), ID="ENV2EPN_link")
-        instantiate("__merged_All_RAM", "Association", ("Encapsulated_PetriNet/Place", "PetriNet/Place"), ID="EPN2PN_transition_link")
-        instantiate("__merged_All_RAM", "Association", ("Encapsulated_PetriNet/Transition", "PetriNet/Transition"), ID="EPN2PN_place_link")
-        transformation_RAMify("__merged_All_RAM", "All_RAM")
-
-        transformation_add_MANUAL(["Requirements"], ["Requirements"], "revise_req")
-        transformation_add_MANUAL(["Requirements", "PW_Environment"], ["PW_Environment"], "revise_environment")
-        transformation_add_MANUAL(["Requirements", "PW_Plant"], ["PW_Plant"], "revise_plant")
-        transformation_add_MANUAL(["Requirements", "PW_Control"], ["PW_Control"], "revise_control")
-        transformation_add_MANUAL(["Requirements", "Query"], ["Query"], "revise_query")
-        transformation_add_MANUAL(["Requirements", "Architecture"], ["Architecture"], "revise_architecture")
-
-        transformation_add_MT("All_RAM", [], ["PW_Plant", "PW_Environment", "PW_Control", "Query", "Architecture", "Requirements"], "make_initial_models", open("models/initialize.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["PW_Plant"], ["Encapsulated_PetriNet"], "plant_to_EPN", open("models/plant_to_EPN.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["PW_Control"], ["Encapsulated_PetriNet"], "control_to_EPN", open("models/control_to_EPN.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["PW_Environment"], ["Encapsulated_PetriNet"], "environment_to_EPN", open("models/environment_to_EPN.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["Encapsulated_PetriNet", "Architecture"], ["Encapsulated_PetriNet"], "combine_EPN", open("models/combine_EPN.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["ReachabilityGraph", "Query"], [], "match", open("models/matches.mvc", 'r').read())
-
-        transformation_add_AL(["PetriNet"], ["ReachabilityGraph"], "reachability", open("models/reachability.alc", 'r').read())
-        transformation_add_AL(["ReachabilityGraph"], [], "bfs", open("models/bfs.alc", 'r').read())
+                ("conformance_mv", "ActionLanguage"),
+                ("core", "CoreFormalism"),
+                ("TM_ReachabilityGraph", "TypeMapping"),
+                ("TM_PetriNet", "TypeMapping"),
+                ("TM_Encapsulated_PetriNet", "TypeMapping"),
+                ("TM_PW_Plant", "TypeMapping"),
+                ("TM_PW_Environment", "TypeMapping"),
+                ("TM_PW_Control", "TypeMapping"),
+                ("TM_Requirements", "TypeMapping"),
+                ("TM_Query", "TypeMapping"),
+                ("TM_Architecture", "TypeMapping"),
+                ("TM_pm_powerwindow", "TypeMapping"),
+                ("TM_SimpleClassDiagrams", "TypeMapping"),
+                ("TM_TypeMapping", "TypeMapping"),
+                ("TM_CoreFormalism", "TypeMapping"),
+                ("TM_ManualOperation", "TypeMapping"),
+                ("TM_bottom", "TypeMapping"),
+                ("TM_ActionLanguage", "TypeMapping"),
+                ("TM_ProcessModel", "TypeMapping"),
+                ("TM_Tracability", "TypeMapping"),
+                ("TM_conformance_mv", "TypeMapping"),
+                ("TM_core", "TypeMapping"),
+            ])
+
+        transformation_add_MANUAL({"Requirements": "Requirements"}, {"Requirements": "Requirements"}, "revise_req")
+        transformation_add_MANUAL({"Requirements": "Requirements", "PW_Environment": "PW_Environment"}, {"PW_Environment": "PW_Environment"}, "revise_environment")
+        transformation_add_MANUAL({"Requirements": "Requirements", "PW_Plant": "PW_Plant"}, {"PW_Plant": "PW_Plant"}, "revise_plant")
+        transformation_add_MANUAL({"Requirements": "Requirements", "PW_Control": "PW_Control"}, {"PW_Control": "PW_Control"}, "revise_control")
+        transformation_add_MANUAL({"Requirements": "Requirements", "Query": "Query"}, {"Query": "Query"}, "revise_query")
+        transformation_add_MANUAL({"Requirements": "Requirements", "Architecture": "Architecture"}, {"Architecture": "Architecture"}, "revise_architecture")
+
+        def tracability_CTRL2EPN():
+            instantiate(None, "Association", ("PW_Control/State", "Encapsulated_PetriNet/Place"), ID="CTRL2EPN_link")
+            instantiate(None, "Association", ("PW_Control/Transition", "Encapsulated_PetriNet/Transition"), ID="CTRL2EPN_tlink")
+
+        def tracability_PLANT2EPN():
+            instantiate(None, "Association", ("PW_Plant/State", "Encapsulated_PetriNet/Place"), ID="PLANT2EPN_link")
+            instantiate(None, "Association", ("PW_Plant/Transition", "Encapsulated_PetriNet/Transition"), ID="PLANT2EPN_tlink")
+
+        def tracability_ENV2EPN():
+            instantiate(None, "Association", ("PW_Environment/Event", "Encapsulated_PetriNet/Place"), ID="ENV2EPN_link")
+
+        def tracability_EPN2PN():
+            instantiate(None, "Association", ("Encapsulated_PetriNet/Place", "PetriNet/Place"), ID="EPN2PN_transition_link")
+            instantiate(None, "Association", ("Encapsulated_PetriNet/Transition", "PetriNet/Transition"), ID="EPN2PN_place_link")
+
+        transformation_add_MT({}, {"PW_Plant": "PW_Plant", "PW_Environment": "PW_Environment", "PW_Control": "PW_Control", "Query": "Query", "Architecture": "Architecture", "Requirements": "Requirements"}, "make_initial_models", open("models/initialize.mvc", 'r').read())
+        transformation_add_MT({"PW_Plant": "PW_Plant"}, {"Encapsulated_PetriNet": "Encapsulated_PetriNet"}, "plant_to_EPN", open("models/plant_to_EPN.mvc", 'r').read(), tracability_PLANT2EPN)
+        transformation_add_MT({"PW_Control": "PW_Control"}, {"Encapsulated_PetriNet": "Encapsulated_PetriNet"}, "control_to_EPN", open("models/control_to_EPN.mvc", 'r').read(), tracability_CTRL2EPN)
+        transformation_add_MT({"PW_Environment": "PW_Environment"}, {"Encapsulated_PetriNet": "Encapsulated_PetriNet"}, "environment_to_EPN", open("models/environment_to_EPN.mvc", 'r').read(), tracability_ENV2EPN)
+        transformation_add_MT({"Encapsulated_PetriNet": "Encapsulated_PetriNet", "Architecture": "Architecture"}, {"PetriNet": "PetriNet"}, "combine_EPN", open("models/combine_EPN.mvc", 'r').read(), tracability_EPN2PN)
+        transformation_add_MT({"ReachabilityGraph": "ReachabilityGraph", "Query": "Query"}, {}, "match", open("models/matches.mvc", 'r').read())
+
+        transformation_add_AL({"PetriNet": "PetriNet"}, {"ReachabilityGraph": "ReachabilityGraph"}, "reachability", open("models/reachability.alc", 'r').read())
+        transformation_add_AL({"ReachabilityGraph": "ReachabilityGraph"}, {}, "bfs", open("models/bfs.alc", 'r').read())
+        transformation_add_AL({"EPN_Plant": "Encapsulated_PetriNet", "EPN_Control": "Encapsulated_PetriNet", "EPN_Environment": "Encapsulated_PetriNet"}, {"Encapsulated_PetriNet": "Encapsulated_PetriNet"}, "merge_EPN", open("models/merge_EPN.alc", 'r').read())
 
         global called
         called = 0
 
         def get_function(filename):
             def func():
+                print("Uploading " + filename)
                 global called
                 if called > len(callbacks):
                     raise Exception("Seemingly called some operation twice!")
@@ -104,7 +135,15 @@ class TestPowerWindow(unittest.TestCase):
                 "revise_architecture": cb_arch,
             }
 
-        process_execute("pm_powerwindow", "pm_", callbacks)
+        try:
+            process_execute("pm_powerwindow", "pm_", callbacks)
+        except:
+            import traceback
+            print(traceback.format_exc())
+
+        if called != 6:
+            print(called)
+            raise Exception("Not executed sufficiently:" + str(called))
 
     @slow
     def test_process_powerwindow_debug(self):
@@ -133,39 +172,69 @@ class TestPowerWindow(unittest.TestCase):
                 ("Architecture", "SimpleClassDiagrams"),
                 ("pm_powerwindow", "ProcessModel"),
                 ("SimpleClassDiagrams", "SimpleClassDiagrams"),
+                ("TypeMapping", "SimpleClassDiagrams"),
                 ("CoreFormalism", "SimpleClassDiagrams"),
                 ("ManualOperation", "SimpleClassDiagrams"),
+                ("bottom", "SimpleClassDiagrams"),
                 ("ActionLanguage", "SimpleClassDiagrams"),
                 ("ProcessModel", "SimpleClassDiagrams"),
                 ("Tracability", "SimpleClassDiagrams"),
-                ("core", "CoreFormalism"),])
-
-        transformation_add_MT_language(["PetriNet", "Encapsulated_PetriNet", "PW_Plant", "PW_Control", "PW_Environment", "Requirements", "ReachabilityGraph", "Query", "Architecture"], "All_RAM")
-        instantiate("__merged_All_RAM", "Association", ("PW_Control/State", "Encapsulated_PetriNet/Place"), ID="CTRL2EPN_link")
-        instantiate("__merged_All_RAM", "Association", ("PW_Control/Transition", "Encapsulated_PetriNet/Transition"), ID="CTRL2EPN_tlink")
-        instantiate("__merged_All_RAM", "Association", ("PW_Plant/State", "Encapsulated_PetriNet/Place"), ID="PLANT2EPN_link")
-        instantiate("__merged_All_RAM", "Association", ("PW_Plant/Transition", "Encapsulated_PetriNet/Transition"), ID="PLANT2EPN_tlink")
-        instantiate("__merged_All_RAM", "Association", ("PW_Environment/Event", "Encapsulated_PetriNet/Place"), ID="ENV2EPN_link")
-        instantiate("__merged_All_RAM", "Association", ("Encapsulated_PetriNet/Place", "PetriNet/Place"), ID="EPN2PN_transition_link")
-        instantiate("__merged_All_RAM", "Association", ("Encapsulated_PetriNet/Transition", "PetriNet/Transition"), ID="EPN2PN_place_link")
-        transformation_RAMify("__merged_All_RAM", "All_RAM")
-
-        transformation_add_MANUAL(["Requirements"], ["Requirements"], "revise_req")
-        transformation_add_MANUAL(["Requirements", "PW_Environment"], ["PW_Environment"], "revise_environment")
-        transformation_add_MANUAL(["Requirements", "PW_Plant"], ["PW_Plant"], "revise_plant")
-        transformation_add_MANUAL(["Requirements", "PW_Control"], ["PW_Control"], "revise_control")
-        transformation_add_MANUAL(["Requirements", "Query"], ["Query"], "revise_query")
-        transformation_add_MANUAL(["Requirements", "Architecture"], ["Architecture"], "revise_architecture")
-
-        transformation_add_MT("All_RAM", [], ["PW_Plant", "PW_Environment", "PW_Control", "Query", "Architecture", "Requirements"], "make_initial_models", open("models/initialize.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["PW_Plant"], ["Encapsulated_PetriNet"], "plant_to_EPN", open("models/plant_to_EPN.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["PW_Control"], ["Encapsulated_PetriNet"], "control_to_EPN", open("models/control_to_EPN.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["PW_Environment"], ["Encapsulated_PetriNet"], "environment_to_EPN", open("models/environment_to_EPN.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["Encapsulated_PetriNet", "Architecture"], ["Encapsulated_PetriNet"], "combine_EPN", open("models/combine_EPN.mvc", 'r').read())
-        transformation_add_MT("All_RAM", ["ReachabilityGraph", "Query"], [], "match", open("models/matches.mvc", 'r').read())
-
-        transformation_add_AL(["PetriNet"], ["ReachabilityGraph"], "reachability", open("models/reachability.alc", 'r').read())
-        transformation_add_AL(["ReachabilityGraph"], [], "bfs", open("models/bfs.alc", 'r').read())
+                ("conformance_mv", "ActionLanguage"),
+                ("core", "CoreFormalism"),
+                ("TM_ReachabilityGraph", "TypeMapping"),
+                ("TM_PetriNet", "TypeMapping"),
+                ("TM_Encapsulated_PetriNet", "TypeMapping"),
+                ("TM_PW_Plant", "TypeMapping"),
+                ("TM_PW_Environment", "TypeMapping"),
+                ("TM_PW_Control", "TypeMapping"),
+                ("TM_Requirements", "TypeMapping"),
+                ("TM_Query", "TypeMapping"),
+                ("TM_Architecture", "TypeMapping"),
+                ("TM_pm_powerwindow", "TypeMapping"),
+                ("TM_SimpleClassDiagrams", "TypeMapping"),
+                ("TM_TypeMapping", "TypeMapping"),
+                ("TM_CoreFormalism", "TypeMapping"),
+                ("TM_ManualOperation", "TypeMapping"),
+                ("TM_bottom", "TypeMapping"),
+                ("TM_ActionLanguage", "TypeMapping"),
+                ("TM_ProcessModel", "TypeMapping"),
+                ("TM_Tracability", "TypeMapping"),
+                ("TM_conformance_mv", "TypeMapping"),
+                ("TM_core", "TypeMapping"),
+            ])
+
+        transformation_add_MANUAL({"Requirements": "Requirements"}, {"Requirements": "Requirements"}, "revise_req")
+        transformation_add_MANUAL({"Requirements": "Requirements", "PW_Environment": "PW_Environment"}, {"PW_Environment": "PW_Environment"}, "revise_environment")
+        transformation_add_MANUAL({"Requirements": "Requirements", "PW_Plant": "PW_Plant"}, {"PW_Plant": "PW_Plant"}, "revise_plant")
+        transformation_add_MANUAL({"Requirements": "Requirements", "PW_Control": "PW_Control"}, {"PW_Control": "PW_Control"}, "revise_control")
+        transformation_add_MANUAL({"Requirements": "Requirements", "Query": "Query"}, {"Query": "Query"}, "revise_query")
+        transformation_add_MANUAL({"Requirements": "Requirements", "Architecture": "Architecture"}, {"Architecture": "Architecture"}, "revise_architecture")
+
+        def tracability_CTRL2EPN():
+            instantiate(None, "Association", ("PW_Control/State", "Encapsulated_PetriNet/Place"), ID="CTRL2EPN_link")
+            instantiate(None, "Association", ("PW_Control/Transition", "Encapsulated_PetriNet/Transition"), ID="CTRL2EPN_tlink")
+
+        def tracability_PLANT2EPN():
+            instantiate(None, "Association", ("PW_Plant/State", "Encapsulated_PetriNet/Place"), ID="PLANT2EPN_link")
+            instantiate(None, "Association", ("PW_Plant/Transition", "Encapsulated_PetriNet/Transition"), ID="PLANT2EPN_tlink")
+
+        def tracability_ENV2EPN():
+            instantiate(None, "Association", ("PW_Environment/Event", "Encapsulated_PetriNet/Place"), ID="ENV2EPN_link")
+
+        def tracability_EPN2PN():
+            instantiate(None, "Association", ("Encapsulated_PetriNet/Place", "PetriNet/Place"), ID="EPN2PN_transition_link")
+            instantiate(None, "Association", ("Encapsulated_PetriNet/Transition", "PetriNet/Transition"), ID="EPN2PN_place_link")
+
+        transformation_add_MT({}, {"PW_Plant": "PW_Plant", "PW_Environment": "PW_Environment", "PW_Control": "PW_Control", "Query": "Query", "Architecture": "Architecture", "Requirements": "Requirements"}, "make_initial_models", open("models/initialize.mvc", 'r').read())
+        transformation_add_MT({"PW_Plant": "PW_Plant"}, {"Encapsulated_PetriNet": "Encapsulated_PetriNet"}, "plant_to_EPN", open("models/plant_to_EPN.mvc", 'r').read(), tracability_PLANT2EPN)
+        transformation_add_MT({"PW_Control": "PW_Control"}, {"Encapsulated_PetriNet": "Encapsulated_PetriNet"}, "control_to_EPN", open("models/control_to_EPN.mvc", 'r').read(), tracability_CTRL2EPN)
+        transformation_add_MT({"PW_Environment": "PW_Environment"}, {"Encapsulated_PetriNet": "Encapsulated_PetriNet"}, "environment_to_EPN", open("models/environment_to_EPN.mvc", 'r').read(), tracability_ENV2EPN)
+        transformation_add_MT({"Encapsulated_PetriNet": "Encapsulated_PetriNet", "Architecture": "Architecture"}, {"PetriNet": "PetriNet"}, "combine_EPN", open("models/combine_EPN.mvc", 'r').read(), tracability_EPN2PN)
+        transformation_add_MT({"ReachabilityGraph": "ReachabilityGraph", "Query": "Query"}, {}, "match", open("models/matches.mvc", 'r').read())
+
+        transformation_add_AL({"PetriNet": "PetriNet"}, {"ReachabilityGraph": "ReachabilityGraph"}, "reachability", open("models/reachability.alc", 'r').read())
+        transformation_add_AL({"ReachabilityGraph": "ReachabilityGraph"}, {}, "bfs", open("models/bfs.alc", 'r').read())
+        transformation_add_AL({"EPN_Plant": "Encapsulated_PetriNet", "EPN_Control": "Encapsulated_PetriNet", "EPN_Environment": "Encapsulated_PetriNet"}, {"Encapsulated_PetriNet": "Encapsulated_PetriNet"}, "merge_EPN", open("models/merge_EPN.alc", 'r').read())
 
         global called
         called = 0
@@ -198,7 +267,11 @@ class TestPowerWindow(unittest.TestCase):
                 "revise_architecture": cb_arch,
             }
 
-        process_execute("pm_powerwindow", "pm_", callbacks)
+        try:
+            process_execute("pm_powerwindow", "pm_", callbacks)
+        except:
+            import traceback
+            print(traceback.format_exc())
 
         if called != 11:
             print(called)

+ 3 - 38
integration/utils.py

@@ -18,8 +18,6 @@ from hutn_compiler.compiler import main as do_compile
 taskname = "test_task"
 INIT_TIMEOUT = 30
 
-
-
 try:
     import pytest
     slow = pytest.mark.skipif(
@@ -55,9 +53,12 @@ def execute(scriptname, parameters=[], wait=False):
 
 def child_kill(pid):
     subprocess.call(["pkill", "-P", "%i" % pid])
+    start = time.time()
     with open(os.devnull, 'w') as null:
         while subprocess.call(["pgrep", "-P", "%i" % pid], stdout=null) != 1:
             time.sleep(0.1)
+            if time.time() > start + 4:
+                subprocess.call(["pkill", "-9", "-P", "%i" % pid])
 
 def kill(process):
     if os.name == "nt":
@@ -79,39 +80,3 @@ def start_mvc():
     address = "http://127.0.0.1:%s" % port
     proc = execute("run_local_modelverse", [str(port)], wait=False)
     return proc, address
-
-def get_constructor(code):
-    code_fragments = code.split("\n")
-    code_fragments = [i for i in code_fragments if i.strip() != ""]
-    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
-    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
-    code_fragments = [i[initial_tabs:] for i in code_fragments]
-    code_fragments.append("")
-    code = "\n".join(code_fragments)
-
-    with open("__constraint.alc", "w") as f:
-        f.write(code)
-        f.flush()
-
-    constructors = do_compile("__constraint.alc", "interface/HUTN/grammars/actionlanguage.g", "CS")
-
-    return constructors
-
-def get_model_constructor(code):
-    # First change multiple spaces to a tab
-    code_fragments = code.split("\n")
-    code_fragments = [i for i in code_fragments if i.strip() != ""]
-    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
-    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
-    code_fragments = [i[initial_tabs:] for i in code_fragments]
-    code_fragments.append("")
-    code = "\n".join(code_fragments)
-
-    with open("__model.mvc", "w") as f:
-        f.write(code)
-        f.flush()
-
-    return get_model_constructor_2("__model.mvc")
-
-def get_model_constructor_2(f):
-    return do_compile(f, "interface/HUTN/grammars/modelling.g", "M") + ["exit"]

+ 3 - 5
interface/HUTN/grammars/actionlanguage.g

@@ -1,8 +1,8 @@
 grammar{
-    start: (include | vardecl | definition | funcdecl | newline)+;
+    start: (include | definition | funcdecl | newline)+;
 
     statement 
-        : (vardecl newline)
+        : (definition newline)
         | (assignment newline)
         | (return newline)
         | (func_call newline)
@@ -64,15 +64,13 @@ grammar{
         : (rvalue LSQUARE expression RSQUARE)
         | ID;
 
-    vardecl: type_specifier ID;
-
 	logical_not: NOT primary;
 
 	invert_sign: MINUS primary;
 
 	keep_sign: PLUS primary;
 
-    definition : type_specifier ID ASSIGN atomvalue;
+    definition : type_specifier ID (ASSIGN atomvalue)?;
 
     include: INCLUDE STRVALUE newline+;
 

+ 1 - 28
interface/HUTN/hutn_compiler/bootstrap_visitor.py

@@ -20,8 +20,6 @@ class BootstrapVisitor(PrimitivesVisitor):
             return "%s_%s" % (self.prepend_name, name) if isinstance(name, int) else name
 
     def dump(self):
-        link_id = 0
-
         if self.main:
             call = self.value(Action("call"))
             access = self.value(Action("access"))
@@ -49,11 +47,7 @@ class BootstrapVisitor(PrimitivesVisitor):
 
                 source = self.rename(source)
                 target = self.rename(target)
-                link_id += 1
-                output.append("Dict _%s(%s, %s, %s)\n" % (link_id, source, value, target))
-                #output.append("Edge _%s_0(%s, %s)\n" % (linkname, source, target))
-                #output.append("Node _%s_2(%s)\n" % (linkname, value))
-                #output.append("Edge _%s_1(_%s_0, _%s_2)\n" % (linkname, linkname, linkname))
+                output.append("Dict (%s, %s, %s)\n" % (source, value, target))
             elif t == "E":
                 name, source, target = data
                 source = source if self.first != source else "initial_IP"
@@ -63,24 +57,3 @@ class BootstrapVisitor(PrimitivesVisitor):
                 target = self.rename(target)
                 output.append("Edge _%s(_%s, _%s)\n" % (name, source, target))
         return ''.join(output)
-
-    """
-    def visit_definition(self, tree):
-        for a in tree.get_children("ID"):
-            name = a.get_tail()[0]
-            return PrimitivesVisitor.visit_definition(self, tree)
-
-    def visit_vardecl(self, tree):
-        if len(tree.get_tail()) > 2:
-            for a in tree.get_children("ID"):
-                name = a.get_tail()[0]
-                return PrimitivesVisitor.visit_vardecl(self, tree)
-        else:
-            return PrimitivesVisitor.visit_vardecl(self, tree)
-
-    def visit_funcdecl(self, tree):
-        for a in tree.get_children("func_name"):
-            for b in a.get_children("ID"):
-                name = b.get_tail()[0]
-                return PrimitivesVisitor.visit_funcdecl(self, tree)
-    """

+ 48 - 21
interface/HUTN/hutn_compiler/compiler.py

@@ -1,6 +1,7 @@
 import cPickle as pickle
 import os
 import sys
+import time
 
 from grammar_compiler_visitor import GrammarCompilerVisitor
 from hutnparser import Parser, Tree
@@ -17,32 +18,37 @@ def read(filename):
   with open(filename, 'r') as f:
     return f.read()
 
-def md5digest(filename):
+def md5digest(data):
     hasher = hashlib.md5()
-    with open(filename, 'rb') as afile:
-        hasher.update(afile.read())
+    hasher.update(data)
     return hasher.hexdigest()
 
-def fetch_cached(filename):
+def fetch_cached(data, mode=None):
     try:
-        md5 = md5digest(filename)
+        md5 = md5digest(data)
         cache_folder = os.path.abspath("%s/../caches/" % (os.path.dirname(os.path.abspath(__file__))))
-        picklefile = cache_folder + "/%s.pickle" % md5
+        if mode is None:
+            picklefile = cache_folder + "/%s.pickle" % md5
+        else:
+            picklefile = cache_folder + "/%s_%s.pickle" % (mode, md5)
         with open(picklefile, "rb") as f:
             return pickle.load(f)
     except:
         return None
 
-def make_cached(filename, data):
-    md5 = md5digest(filename)
+def make_cached(original_data, data, mode=None):
+    md5 = md5digest(original_data)
     cache_folder = os.path.abspath("%s/../caches/" % (os.path.dirname(os.path.abspath(__file__))))
-    picklefile = cache_folder + "/%s.pickle" % md5
+    if mode is None:
+        picklefile = cache_folder + "/%s.pickle" % md5
+    else:
+        picklefile = cache_folder + "/%s_%s.pickle" % (mode, md5)
     with open(picklefile, "wb") as f:
         pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
 
 def do_parse(inputfile, grammarfile):
     if grammarfile not in parsers:
-        grammar = fetch_cached(grammarfile)
+        grammar = fetch_cached(read(grammarfile))
         if grammar is None:
             result = parser = Parser(Grammar(), hide_implicit = True).parse(read(grammarfile))
             if result['status'] != Parser.Constants.Success:
@@ -55,18 +61,24 @@ def do_parse(inputfile, grammarfile):
             grammar = Grammar()          
             grammar.rules = structure['rules']
             grammar.tokens = structure['tokens']        
-            make_cached(grammarfile, grammar)
+            make_cached(read(grammarfile), grammar)
         parsers[grammarfile] = grammar
     else:
         grammar = parsers[grammarfile]
 
-    result = fetch_cached(inputfile)
+    result = fetch_cached(read(inputfile))
     if result is None:
         result = Parser(grammar, line_position = True).parse(read(inputfile))
         if result['status'] != Parser.Constants.Success:
-            msg = "%s:%s:%s: %s" % (inputfile, result["line"], result["column"], result["text"])
+            lines = open(inputfile, 'r').readlines()
+            begin_line = max(result["line"] - 3, 0)
+            end_line = min(result["line"] + 3, len(lines))
+            lines = lines[begin_line:end_line]
+            lines = ["%s:   %s" % (begin_line + i + 1, line) for i, line in enumerate(lines)]
+            lines = "".join(lines)
+            msg = "%s:%s:%s: %s\nContext:\n%s" % (inputfile, result["line"], result["column"], result["text"], lines)
             raise Exception(msg)
-        make_cached(inputfile, result)
+        make_cached(read(inputfile), result)
 
     return result
 
@@ -88,15 +100,22 @@ def find_file(filename, include_paths):
     else:
         raise Exception("Could not resolve file %s. Tried: %s" % (filename, attempts))
 
-def do_compile(inputfile, grammarfile, visitors=[], include_paths = []):
+def do_compile(inputfile, grammarfile, visitors=[], include_paths = [], mode=""):
     import os.path
     global working_file
     working_file = os.path.abspath(inputfile)
 
     result = do_parse(inputfile, grammarfile)
+
     error = result["status"] != Parser.Constants.Success
     if error:
-        msg = "%s:%s:%s: %s" % (inputfile, result["line"], result["column"], result["text"])
+        lines = open(working_file, 'r').readlines()
+        begin_line = max(result["line"] - 3, 0)
+        end_line = max(result["line"] + 3, len(lines))
+        lines = lines[begin_line:end_line]
+        lines = ["%s:   %s" % (begin_line + i + 1, line) for i, line in enumerate(lines)]
+        lines = "".join(lines)
+        msg = "%s:%s:%s: %s\nContext:\n%s" % (inputfile, result["line"], result["column"], result["text"], lines)
         raise Exception(msg)
     else:
         for child in result["tree"].tail:
@@ -132,14 +151,22 @@ def do_compile(inputfile, grammarfile, visitors=[], include_paths = []):
             else:
                 # The outer for finally finished, so there were no includes remaining, thus terminate the infinite while loop
                 break
+    tree_data = pickle.dumps(result["tree"], pickle.HIGHEST_PROTOCOL)
+    new_result = fetch_cached(tree_data, mode)
+    if new_result is None:
+        result["tree"].fix_tracability(inputfile)
 
-    result["tree"].fix_tracability(inputfile)
+        for visitor in visitors:
+            visitor.visit(result["tree"])
 
-    for visitor in visitors:
-        visitor.visit(result["tree"])
+        if visitors:
+            result = visitors[-1].dump()
+            make_cached(tree_data, result, mode)
+    else:
+        result = new_result
 
     if visitors:
-        return visitors[-1].dump()
+        return result
 
 def main(input_file, grammar_file, mode, args=[]):
     from prettyprint_visitor import PrettyPrintVisitor
@@ -161,7 +188,7 @@ def main(input_file, grammar_file, mode, args=[]):
     }
     try:
         visitors = [v(args) for v in modes[mode]]
-        result = do_compile(input_file, grammar_file, visitors)
+        result = do_compile(input_file, grammar_file, visitors, mode=mode)
     except CachedException:
         return True
     return result

+ 22 - 23
interface/HUTN/hutn_compiler/constructors_visitor.py

@@ -8,8 +8,7 @@ class ConstructorsVisitor(Visitor):
         self.free_id = 0
 
     def dump(self):
-        return self.constructors
-        # return pickle.dumps(self.constructors, pickle.HIGHEST_PROTOCOL)
+        return [len(self.constructors)] + self.constructors
 
     def add_constructors(self, *constructors):
         self.constructors.extend(constructors)
@@ -55,11 +54,6 @@ class ConstructorsVisitor(Visitor):
             self.add_constructors("declare", symbol.node)
             self.free_id += 1
 
-    def visit_vardecl(self, tree):
-        symbol = self.get_symbol(tree)
-        self.declare(symbol)
-        return True
-
     def visit_assignment(self, tree):
         self.add_constructors("assign")
         self.visit(tree.get_tail()[0])
@@ -111,7 +105,11 @@ class ConstructorsVisitor(Visitor):
             {"value": tree.get_tail()[0].get_text()[1:]})
 
     def visit_string(self, tree):
-        self.add_constructors("const", tree.get_text()[1:-1])
+        v = tree.get_text()[1:-1]
+        v = v.replace("\\n", "\n")
+        v = v.replace("\\t", "\t")
+        v = v.replace("\\\"", "\"")
+        self.add_constructors("const", v)
 
     def visit_integer(self, tree):
         self.add_constructors("const", int(tree.get_text()))
@@ -281,22 +279,23 @@ class ConstructorsVisitor(Visitor):
     def visit_definition(self, tree):
         # First declare it
         symbol = self.get_symbol(tree)
-        symbol.node = symbol.name
+        self.declare(symbol)
 
-        # Now generate constructors
-        self.add_constructors("global", symbol.name)
-
-        # Determine whether it is just a constant, or a deref
-        atom = tree.get_child("atomvalue")
-        if atom.get_child("deref"):
-            # Deref
-            dest = atom.get_child("deref").get_child("ANYTHING")
-            if dest is None:
-                # Just an empty questionmark!
-                self.add_constructors("empty")
+        if tree.get_children("ASSIGN"):
+            # Determine whether it is just a constant, or a deref
+            atom = tree.get_child("atomvalue")
+            if atom.get_child("deref"):
+                # Deref
+                dest = atom.get_child("deref").get_child("ANYTHING")
+                if dest is None:
+                    # Just an empty questionmark!
+                    self.add_constructors("empty")
+                else:
+                    self.add_constructors("deref", dest.get_text())
             else:
-                self.add_constructors("deref", dest.get_text())
+                # Constant
+                self.visit(atom)
         else:
-            # Constant
-            self.visit(atom)
+            self.add_constructors("none")
+
         return True

+ 2 - 2
interface/HUTN/hutn_compiler/model_bootstrap_visitor.py

@@ -18,7 +18,7 @@ class ModelBootstrapVisitor(Visitor):
         self.includes = []
 
     def dump(self):
-        return self.code
+        return self.code + "\treturn!"
 
     def __getattr__(self, attr):
         if attr.startswith("visit_"):
@@ -166,7 +166,7 @@ class ModelBootstrapVisitor(Visitor):
             # Value attribute
             attr_value = tree.get_children("value")[0].get_tail()[0]
             if attr_value.head == "STRVALUE":
-                attr_value = attr_value.get_text()[1:-1]
+                attr_value = '"%s"' %  attr_value.get_text()[1:-1]
             elif attr_value.head == "TRUE":
                 attr_value = True
             elif attr_value.head == "FALSE":

+ 1 - 1
interface/HUTN/hutn_compiler/model_visitor.py

@@ -15,7 +15,7 @@ class ModelVisitor(Visitor):
         self.includes = []
 
     def dump(self):
-        return self.constructors
+        return [len(self.constructors)] + self.constructors
 
     def __getattr__(self, attr):
         if attr.startswith("visit_"):

+ 29 - 38
interface/HUTN/hutn_compiler/primitives_visitor.py

@@ -104,22 +104,6 @@ class PrimitivesVisitor(Visitor):
             self.dict(primitives[i], "next", primitives[i+1])
         self.last_instruction = primitives[-1]
 
-    def visit_vardecl(self, tree):
-        symbol = self.get_symbol(tree)
-
-        if symbol.is_global:
-            d = self.value(Action("global"))
-            n = self.value(symbol.name)
-        else:
-            d = self.value(Action("declare"))
-            n = self.node()
-
-        symbol.node = n
-        self.dict(d, "var", n)
-        self.debug(d, tree)
-
-        self.set_primitive(tree, d)
-
     def visit_assignment(self, tree):
         self.visit_children(tree)
 
@@ -215,7 +199,7 @@ class PrimitivesVisitor(Visitor):
 
     def visit_lvalue(self, tree):
         symbol = self.get_symbol(tree)
-        if symbol.name in ["input", "output"]:
+        if symbol.name in ["__input", "__output"]:
             return
         r = self.value(Action("resolve"))
         # print symbol.name, symbol.is_func(), symbol.node
@@ -343,7 +327,7 @@ class PrimitivesVisitor(Visitor):
 
     def pre_visit_funcdecl(self, tree):
         symbol = self.get_symbol(tree)
-        if symbol.name in ["input", "output"]:
+        if symbol.name in ["__input", "__output"]:
             return
 
         # TODO: fix funcdecl special case: "X function f(...) = ..."
@@ -374,7 +358,7 @@ class PrimitivesVisitor(Visitor):
 
     def visit_funcdecl(self, tree):
         symbol = self.get_symbol(tree)
-        if symbol.name in ["input", "output"]:
+        if symbol.name in ["__input", "__output"]:
             return
 
         func_body = tree.get_child("func_body")
@@ -429,35 +413,42 @@ class PrimitivesVisitor(Visitor):
 
     def visit_definition(self, tree):
         symbol = self.get_symbol(tree)
-        root = self.value(symbol.name)
 
-        declare = self.value(Action("global"))
+        if symbol.is_global:
+            declare = self.value(Action("global"))
+            root = self.value(symbol.name)
+        else:
+            declare = self.value(Action("declare"))
+            root = self.node()
+
         self.dict(declare, "var", root)
         self.debug(declare, tree)
 
         symbol.node = root
 
-        resolve = self.value(Action("resolve"))
-        self.dict(resolve, "var", root)
-
-        assign = self.value(Action("assign"))
-        self.dict(assign, "var", resolve)
+        if tree.get_children("ASSIGN"):
+            resolve = self.value(Action("resolve"))
+            self.dict(resolve, "var", root)
 
-        self.visit_atomvalue(tree.get_tail()[-1])
-        value = self.get_primitive(tree.get_tail()[-1])
+            assign = self.value(Action("assign"))
+            self.dict(assign, "var", resolve)
 
-        if value is None:
-            call = self.value(Action("call"))
-            access = self.value(Action("access"))
-            resolve = self.value(Action("resolve"))
-            self.dict(call, "func", access)
-            self.dict(access, "var", resolve)
-            self.dict(resolve, "var", self.value("create_node"))
-            value = call
+            self.visit_atomvalue(tree.get_tail()[-1])
+            value = self.get_primitive(tree.get_tail()[-1])
 
-        self.dict(assign, "value", value)
+            if value is None:
+                call = self.value(Action("call"))
+                access = self.value(Action("access"))
+                resolve = self.value(Action("resolve"))
+                self.dict(call, "func", access)
+                self.dict(access, "var", resolve)
+                self.dict(resolve, "var", self.value("create_node"))
+                value = call
 
-        self.set_primitive(tree, (declare, assign))
+            self.dict(assign, "value", value)
+            self.set_primitive(tree, (declare, assign))
+        else:
+            self.set_primitive(tree, declare)
 
     def visit_parameter(self, tree):
         n = self.node()

+ 4 - 2
interface/HUTN/hutn_compiler/semantics_visitor.py

@@ -569,8 +569,10 @@ class SemanticsVisitor(Visitor):
                 self.perform_implicit_cast(tree, expressions[i], arg_type,
                                            param_type)
 
-        if symbol.name in ["input", "output"]:
-            tree.head = symbol.name
+        if symbol.name == "__input":
+            tree.head = "input"
+        elif symbol.name == "__output":
+            tree.head = "output"
 
     def visit_input(self, tree):
         pass  # no need to visit it again

+ 2 - 0
interface/HUTN/includes/compiler.alh

@@ -0,0 +1,2 @@
+Element function compile_code(code : String)
+Element function compile_model(code : String, model : Element)

+ 1 - 0
interface/HUTN/includes/conformance_finding.alh

@@ -0,0 +1 @@
+Boolean function find_type_mapping(model : Element)

+ 1 - 0
interface/HUTN/includes/conformance_scd.alh

@@ -1,3 +1,4 @@
+Boolean function wrap_conformance(model : Element)
 Boolean function is_direct_instance(model: Element, instance: String, type: String)
 Boolean function is_nominal_instance(model: Element, instance: String, type: String)
 Boolean function is_nominal_subtype(metamodel : Element, subclass : String, superclass : String)

+ 1 - 0
interface/HUTN/includes/constructors.alh

@@ -1 +1,2 @@
 Action function construct_function()
+Action function construct_function_list(list : Element)

+ 10 - 0
interface/HUTN/includes/core_algorithm.alh

@@ -1,2 +1,12 @@
 Void function initialize_core()
 Void function new_task()
+String function get_service_id(name : String)
+
+Element function merge_models(models_dict : Element, operation_id : String)
+Element function split_model(model : Element, metamodels_dict : Element)
+Element function get_model(model_name : String, metamodel_name : String)
+Void function store_model(model_name : String, metamodel_name : String, model : Element)
+String function get_ramified_metamodel(model_name : String)
+
+// This should be removed, as it allows everyone to alter the core...
+Element core

+ 2 - 1
interface/HUTN/includes/io.alh

@@ -1,2 +1,3 @@
 Element function input()
-Element function output(value : Element)
+Void function output(value : Element)
+Element function input_timeout(timeout : Float)

+ 0 - 1
interface/HUTN/includes/model_management.alh

@@ -1,5 +1,4 @@
 Element function model_fuse(models : Element)
 Element function model_copy(model : Element)
-Element function model_retype_on_name(model : Element, new_MM : Element, operation : String, name : String)
 Element function model_join(models : Element, metamodel : Element, tracability : Element)
 Element function model_split(merged_model : Element, models : Element, tracability : Boolean)

+ 2 - 0
interface/HUTN/includes/modelling.alh

@@ -25,3 +25,5 @@ String function model_define_attribute(model : Element, elem : String, name : St
 Element function construct_model_raw(metamodel : Element)
 Element function get_func_AL_model(model : Element)
 Void function add_code_model(model : Element, export_name : String, code : Element)
+String function read_type(model : Element, name : String)
+Element function construct_model_list(metamodel : Element, list : Element)

+ 0 - 3
interface/HUTN/includes/object_operations.alh

@@ -5,12 +5,9 @@ Element function allOutgoingAssociationInstances(model: Element, source_name : S
 Element function allIncomingAssociationInstances(model: Element, target_name : String, assoc_name: String)
 Element function getAttributeList(model: Element, element: String)
 Element function getInstantiatableAttributes(model: Element, element: String)
-String function reverseKeyLookup(a: Element, b: Element)
-Element function reverseKeyLookupMulti(a: Element, b: Element)
 String function print_dict(dict : Element)
 String function readAssociationSource(model : Element, name : String)
 String function readAssociationDestination(model : Element, name : String)
 Element function allAssociationDestinations(model : Element, name : String, association_type : String)
 Element function allAssociationOrigins(model : Element, name : String, association_type : String)
 Element function allowedAssociationsBetween(model : Element, src : String, dst : String)
-String function read_type(model : Element, name : String)

+ 16 - 3
interface/HUTN/includes/primitives.alh

@@ -47,11 +47,11 @@ Float function float_addition(a: Float, b: Float)
 Float function float_subtraction(a: Float, b: Float) 
 Float function float_multiplication(a: Float, b: Float) 
 Float function float_division(a: Float, b: Float) 
+Float function float_neg(a: Float)
 Boolean function float_gt(a: Float, b: Float) 
 Boolean function float_gte(a: Float, b: Float) 
 Boolean function float_lt(a: Float, b: Float) 
 Boolean function float_lte(a: Float, b: Float) 
-Boolean function float_neg(a: Float)
 Integer function integer_addition(a: Integer, b: Integer)
 Integer function integer_subtraction(a: Integer, b: Integer) 
 Integer function integer_multiplication(a: Integer, b: Integer) 
@@ -67,12 +67,16 @@ Element function list_append(a: Element, b: Element)
 Element function list_insert(a: Element, b: Element, c: Integer) 
 Element function list_delete(a: Element, b: Integer) 
 Integer function list_len(a: Element) 
+Boolean function list_in(a : Element, b : Element)
 Element function set_add(a: Element, b: Element) 
+Element function set_add_node(a: Element, b: Element) 
 Element function set_pop(a: Element) 
+Element function set_read(a : Element)
 Element function set_remove(a: Element, b: Element) 
 Boolean function set_in(a: Element, b: Element) 
 Element function set_remove_node(a: Element, b: Element) 
 Element function set_in_node(a: Element, b: Element) 
+Integer function set_len(a: Element)
 String function string_join(a: String, b: String) 
 String function string_get(a: String, b: Integer) 
 String function string_substr(a: String, b: Integer, c: Integer) 
@@ -92,21 +96,30 @@ Boolean function is_physical_boolean(a : Element)
 Boolean function has_value(a : Element)
 Float function time()
 String function hash(a : String)
-
+Void function sleep(a : Float)
+Void function interruptable_sleep(a : Float)
 Element function exec(a : Element)
 Element function resolve(var_name : String)
 Boolean function has_input()
 Element function list_pop(lst : Element, index : Integer)
+Element function list_pop_final(lst : Element)
 Element function set_copy(set : Element)
 String function set_to_string(set : Element)
 String function list_to_string(set : Element)
 String function dict_to_string(dict : Element)
 Element function set_overlap(sa : Element, sb : Element)
+Element function set_difference(sa : Element, sb : Element)
 Element function set_equality(sa : Element, sb : Element)
 Element function dict_eq(da : Element, db : Element)
 Element function dict_copy(dict : Element)
 Element function set_to_list(s : Element)
 Element function create_tuple(a : Element, b : Element)
 Void function dict_overwrite(a : Element, b : Element, c : Element)
-Element function set_merge(sa : Element, sb : Element)
+Void function set_merge(sa : Element, sb : Element)
 Element function make_reverse_dictionary(dict : Element)
+Element function set_create()
+Element function list_create()
+Element function dict_create()
+String function reverseKeyLookup(a: Element, b: Element)
+Element function reverseKeyLookupMulti(a: Element, b: Element)
+Element function dict_values(dict : Element)

+ 7 - 0
interface/HUTN/includes/services.alh

@@ -0,0 +1,7 @@
+String function comm_newPort()
+Boolean function comm_hasInput(comm : String)
+Void function comm_set(comm : String, value : Element)
+Element function comm_get(comm : String)
+String function comm_connect(service : String)
+Void function comm_close(comm : String)
+Element function comm_get_list(comm : String)

+ 6 - 0
interface/HUTN/includes/typing.alh

@@ -0,0 +1,6 @@
+Element function get_type_mapping_as_dict(model : Element)
+Element function get_elements_typed_by(model : Element, type : String)
+String function read_type(model : Element, name : String)
+Void function retype(model : Element, element : String, type : String)
+Element function new_type_mapping()
+Void function remove_type(model : Element, name : String)

+ 7 - 0
interface/HUTN/includes/utils.alh

@@ -0,0 +1,7 @@
+String function JSON_print(model : Element)
+Element function list_reverse(lst : Element)
+Element function list_splice(lst : Element, start : Integer, end : Integer)
+Void function list_extend(lst : Element, ext : Element)
+Void function set_difference(set1 : Element, set2 : Element)
+String function get_taskname()
+Void function sleep(seconds : Float)

+ 0 - 0
interface/HUTN/test/constructor_compilation_action_language/expected/action


برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است