Simon Van Mierlo 9 лет назад
Родитель
Сommit
a640553d07
46 измененных файлов с 1360 добавлено и 3912 удалено
  1. 0 75
      addis/PM_Example.mvc
  2. 0 164
      addis/PM_MetaModel.mvc
  3. 0 97
      addis/PM_example2.mvc
  4. 0 2111
      addis/PM_to_SCCD.mvc
  5. 0 406
      addis/SCCD_Example.mvc
  6. 0 271
      addis/SCCD_MetaModel.mvc
  7. 0 45
      addis/Test_PM2SCCD.py
  8. 11 4
      bootstrap/compiler.alc
  9. 0 12
      bootstrap/constructors.alc
  10. 45 6
      bootstrap/core_algorithm.alc
  11. 11 2
      bootstrap/mini_modify.alc
  12. 0 17
      bootstrap/modelling.alc
  13. 44 43
      bootstrap/transform.alc
  14. 1 1
      hybrid_server/run_mvk_server.py
  15. 0 117
      hybrid_server/socket2event.py
  16. 11 4
      integration/test_powerwindow.py
  17. 1 1
      integration/utils.py
  18. 1 1
      interface/HUTN/grammars/actionlanguage.g
  19. 2 0
      interface/HUTN/grammars/modelling.g
  20. 3 0
      interface/HUTN/hutn_compiler/model_visitor.py
  21. 6 0
      interface/HUTN/test/modelling_language/code/multiline.mvc
  22. 1 0
      interface/HUTN/test/modelling_language/expected/multiline
  23. 5 2
      interface/HUTN/test/modelling_language/test_compile.py
  24. 1 1
      kernel/mvk_server/run_mvk_server.py
  25. 0 117
      kernel/mvk_server/socket2event.py
  26. 8 8
      models/SCCD_execute.alc
  27. 1 0
      models/merge_EPN.alc
  28. 1 5
      models/pm_req_analyse_debug.mvc
  29. 29 17
      scripts/HUTN_service.py
  30. 1 1
      scripts/run_basic_tests.py
  31. 22 11
      scripts/run_local_modelverse.py
  32. 1 1
      state/mvs_server/run_mvs_server.py
  33. 0 117
      state/mvs_server/socket2event.py
  34. 106 0
      unit/log_output.py
  35. 39 0
      unit/log_output.xml
  36. 15 2
      unit/test_all.py
  37. 1 1
      unit/utils.py
  38. 371 0
      wrappers/http_client.py
  39. 192 0
      wrappers/http_client.xml
  40. 249 228
      wrappers/modelverse.py
  41. 115 0
      wrappers/poll_print.py
  42. 43 0
      wrappers/poll_print.xml
  43. 7 7
      wrappers/test.py
  44. 16 11
      wrappers/test_SCCD.py
  45. 0 3
      wrappers/test_service.py
  46. 0 3
      wrappers/test_service_client.py

+ 0 - 75
addis/PM_Example.mvc

@@ -1,75 +0,0 @@
-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"
-}

+ 0 - 164
addis/PM_MetaModel.mvc

@@ -1,164 +0,0 @@
-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
-}

+ 0 - 97
addis/PM_example2.mvc

@@ -1,97 +0,0 @@
-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"
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 2111
addis/PM_to_SCCD.mvc


+ 0 - 406
addis/SCCD_Example.mvc

@@ -1,406 +0,0 @@
-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!
-        $
-    }
-}

+ 0 - 271
addis/SCCD_MetaModel.mvc

@@ -1,271 +0,0 @@
-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"!
-        $
-    }

+ 0 - 45
addis/Test_PM2SCCD.py

@@ -1,45 +0,0 @@
-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")

+ 11 - 4
bootstrap/compiler.alc

@@ -22,7 +22,10 @@ Element function generic_compile(code : String, port : String):
 
 Element function compile_code(code : String):
 	String port
-	port = comm_connect("compiler")
+	port = ""
+	while (port == ""):
+		port = comm_connect("compiler")
+
 	comm_set(port, "code")
 
 	Element list
@@ -34,9 +37,13 @@ Element function compile_code(code : String):
 	else:
 		return construct_function_list(list)!
 
-Element function compile_model(code : String, model : Element):
+Element function compile_model(code : String, metamodel : Element):
 	String port
-	port = comm_connect("compiler")
+	port = ""
+	while (port == ""):
+		port = comm_connect("compiler")
+		sleep(0.5)
+
 	comm_set(port, "model")
 
 	Element list
@@ -46,4 +53,4 @@ Element function compile_model(code : String, model : Element):
 		return read_root()!
 
 	else:
-		return construct_model_list(model, list)!
+		return construct_model_list(instantiate_model(metamodel), list)!

+ 0 - 12
bootstrap/constructors.alc

@@ -8,18 +8,6 @@ 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

+ 45 - 6
bootstrap/core_algorithm.alc

@@ -12,6 +12,7 @@ include "metamodels.alh"
 include "utils.alh"
 include "conformance_finding.alh"
 include "typing.alh"
+include "compiler.alh"
 
 String core_model_location = "models/core"
 
@@ -74,6 +75,8 @@ String function get_instanceOf_link(model_id : String, metamodel_id : String):
 		log("WARNING: multiple instanceOf relations were detected for this model; picking one at random!")
 	elif (set_len(all_links) == 0):
 		log("No types found!")
+		log("Source model: " + cast_v2s(read_attribute(core, model_id, "name")))
+		log("Target meta-model: " + cast_v2s(read_attribute(core, metamodel_id, "name")))
 		return read_root()!
 	
 	choice = set_pop(all_links)
@@ -996,7 +999,11 @@ String function cmd_model_add(type : String, name : String):
 							return "Type is not typed by formalisms/SimpleClassDiagrams: " + type!
 
 						output("Waiting for model constructors...")
-						new_model = construct_model_raw(mm)
+						new_model = compile_model(input(), mm)
+
+						if (element_eq(new_model, read_root())):
+							return "Compilation error"!
+
 						model_create(new_model, name, type_id, "Model")
 						return "Success"!
 					else:
@@ -1294,7 +1301,11 @@ String function cmd_model_overwrite(model_name : String, metamodel_name : String
 					return "Metamodel does not conform to formalisms/SimpleClassDiagrams: " + metamodel_name!
 
 				output("Waiting for model constructors...")
-				new_model = construct_model_raw(mm)
+				new_model = compile_model(input(), mm)
+
+				if (element_eq(new_model, read_root())):
+					return "Compilation error"!
+
 				model_overwrite(new_model, model_id, get_entry_id(metamodel_name))
 				return "Success"!
 			else:
@@ -1516,7 +1527,12 @@ String function transformation_add(source_models : Element, target_models : Elem
 		elif (operation_type == "actionlanguage"):
 			// Finished with all information, now create the model itself!
 			output("Waiting for code constructors...")
-			add_code_model(get_full_model(get_entry_id("formalisms/ActionLanguage"), get_entry_id("formalisms/SimpleClassDiagrams")), "AL/" + operation_name, construct_function())
+			Element compiled
+			compiled = compile_code(input())
+			if (element_eq(compiled, read_root())):
+				return "Compilation error"!
+
+			add_code_model(get_full_model(get_entry_id("formalisms/ActionLanguage"), get_entry_id("formalisms/SimpleClassDiagrams")), "AL/" + operation_name, compiled)
 			model_create(import_node("AL/" + operation_name), operation_name, get_entry_id("formalisms/ActionLanguage"), "ActionLanguage")
 			model_id = get_entry_id(operation_name)
 
@@ -1648,7 +1664,9 @@ String function cmd_transformation_add_MT(source_models : Element, target_models
 		String new_model
 		// Finished with all information, now create the model itself!
 		output("Waiting for model constructors...")
-		new_model = construct_model_raw(get_full_model(ramified_metamodel_id, get_entry_id("formalisms/SimpleClassDiagrams")))
+		new_model = compile_model(input(), get_full_model(ramified_metamodel_id, get_entry_id("formalisms/SimpleClassDiagrams")))
+		if (element_eq(new_model, read_root())):
+			return "Compilation error"!
 		model_create(new_model, operation_name, ramified_metamodel_id, "ModelTransformation")
 		model_id = get_entry_id(operation_name)
 
@@ -1950,10 +1968,8 @@ String function cmd_service_register(service_name : String):
 		output("Success: " + get_taskname())
 
 		// Wait until we can stop the service
-		log("Waiting for service_stop")
 		while (cast_v2s(input()) != "\"service_stop\""):
 			output("Service is running on this task: stop it by sending 'service_stop'")
-		log("Finished")
 
 		model_delete_element(core, service)
 
@@ -2002,6 +2018,27 @@ String function cmd_transformation_signature(transformation_name : String):
 			return "Model is not an operation: " + transformation_name!
 	else:
 		return "No such operation: " + transformation_name!
+
+String function cmd_model_types(model_name : String):
+	if (get_entry_id(model_name) != ""):
+		String model_id
+		model_id = get_entry_id(model_name)
+
+		Element types
+		String type
+		String result
+
+		result = "Success: "
+		types = allAssociationDestinations(core, model_id, "instanceOf")
+		while (set_len(types) > 0):
+			type = set_pop(types)
+			log("Checking type: " + cast_v2s(type))
+			log("Name attr: " + cast_v2s(read_attribute(core, type, "name")))
+			result = string_join(result, full_name(type) + "\n")
+
+		return result!
+	else:
+		return "No such model: " + model_name!
 	
 String function cmd_element_list_nice(model_name : String, metamodel_name : String):
 	if (get_entry_id(model_name) != ""):
@@ -2149,6 +2186,8 @@ Void function user_function_skip_init(user_id : String):
 		elif (cmd == "service_poll"):
 			// TODO
 			cmd = "FAIL"
+		elif (cmd == "model_types"):
+			output(cmd_model_types(single_input("Model name?")))
 		else:
 			output("Unknown command: " + cmd)
 

+ 11 - 2
bootstrap/mini_modify.alc

@@ -7,6 +7,7 @@ include "io.alh"
 include "metamodels.alh"
 include "modelling.alh"
 include "typing.alh"
+include "compiler.alh"
 
 Boolean verbose = True
 
@@ -87,7 +88,10 @@ String function cmd_upload(write : Boolean, model : Element):
 	Element new_model
 	if (write):
 		output("Waiting for model constructors...")
-		new_model = construct_model_raw(model["metamodel"])
+		new_model = compile_model(input(), model["metamodel"])
+		if (element_eq(new_model, read_root())):
+			return "Compilation error"!
+
 		dict_overwrite(model, "model", new_model["model"])
 		set_type_mapping(model, get_type_mapping(new_model))
 		return "Success"!
@@ -172,7 +176,12 @@ String function cmd_attr_add_code(write : Boolean, model : Element, element_name
 			attrs = getAttributeList(model, element_name)
 			if (set_in(dict_keys(attrs), attr_name)):
 				output("Waiting for code constructors...")
-				instantiate_attribute_code(model, element_name, attr_name, construct_function())
+				Element compiled
+				compiled = compile_code(input())
+				if (element_eq(compiled, read_root())):
+					return "Compilation error"!
+
+				instantiate_attribute_code(model, element_name, attr_name, compiled)
 				return "Success"!
 			else:
 				return "Attribute not found: " + attr_name!

+ 0 - 17
bootstrap/modelling.alc

@@ -537,23 +537,6 @@ String function add_AL(model : Element, element : Element):
 
 	return reverseKeyLookup(model["model"], element)!
 
-Element function construct_model_raw(metamodel : Element):
-	String command
-	Element model
-
-	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
 

+ 44 - 43
bootstrap/transform.alc

@@ -93,13 +93,47 @@ Element function get_possible_bindings(host_model : Element, schedule_model : El
 	typename = read_type(schedule_model, current_element)
 	original_typename = string_substr(typename, 4, string_len(typename))
 	guaranteed_instance = False
+
+	// Is a node, so find whether or not there are some connections that are already resolved
+	Element ic
+	Element oc
+	String poll
+	String value
+
+	oc = allOutgoingAssociationInstances(schedule_model, current_element, "PreElement")
+	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
+			value = readAssociationSource(host_model, map[read_attribute(schedule_model, poll, "label")])
+			if (bool_not(set_in(options, value))):
+				set_add(options, value)
+
+	if (set_len(options) < 2):
+		ic = allIncomingAssociationInstances(schedule_model, current_element, "PreElement")
+		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
+				value = readAssociationDestination(host_model, map[read_attribute(schedule_model, poll, "label")])
+				if (bool_not(set_in(options, value))):
+					set_add(options, value)
+		
+	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 (set_len(options) > 1):
+		// Multiple "only" options, which will not work out: no options!
+		return set_create()!
 	
 	if (is_edge(schedule_model["model"][current_element])):
 		Boolean src_in
 		Boolean dst_in
 		// Is an edge, so check for already bound source/target
-		src_label = read_attribute(schedule_model, reverseKeyLookup(schedule_model["model"], read_edge_src(schedule_model["model"][current_element])), "label")
-		dst_label = read_attribute(schedule_model, reverseKeyLookup(schedule_model["model"], read_edge_dst(schedule_model["model"][current_element])), "label")
+		src_label = read_attribute(schedule_model, readAssociationSource(schedule_model, current_element), "label")
+		dst_label = read_attribute(schedule_model, readAssociationDestination(schedule_model, current_element), "label")
 		src_in = set_in(dict_keys(map), src_label)
 		dst_in = set_in(dict_keys(map), dst_label)
 
@@ -107,56 +141,22 @@ 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 (set_len(options) > 0):
+				options = set_overlap(options, allOutgoingAssociationInstances(host_model, map[src_label], original_typename))
 			if (set_len(options) > 0):
 				options = set_overlap(options, allIncomingAssociationInstances(host_model, map[dst_label], original_typename))
 
 		elif (src_in):
 			// Source is bound
-			options = allOutgoingAssociationInstances(host_model, map[src_label], original_typename)
+			options = set_overlap(options, allOutgoingAssociationInstances(host_model, map[src_label], original_typename))
 
 		elif (dst_in):
 			// Destination is bound
-			options = allIncomingAssociationInstances(host_model, map[dst_label], original_typename)
+			options = set_overlap(options, allIncomingAssociationInstances(host_model, map[dst_label], original_typename))
 
 		else:
 			// Neither is bound, so just get all of them
-			options = allInstances(host_model, original_typename)
-	else:
-		// Is a node, so find whether or not there are some connections that are already resolved
-		Element ic
-		Element oc
-		String poll
-		String value
-
-		oc = allOutgoingAssociationInstances(schedule_model, current_element, "PreElement")
-		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
-				value = readAssociationSource(host_model, map[read_attribute(schedule_model, poll, "label")])
-				if (bool_not(set_in(options, value))):
-					set_add(options, value)
-
-		if (set_len(options) < 2):
-			ic = allIncomingAssociationInstances(schedule_model, current_element, "PreElement")
-			String value
-			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
-					value = readAssociationDestination(host_model, map[read_attribute(schedule_model, poll, "label")])
-					if (bool_not(set_in(options, value))):
-						set_add(options, value)
-			
-		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 (set_len(options) > 1):
-			// Multiple "only" options, which will not work out: no options!
-			return set_create()!
+			options = options
 
 	// Filter options further
 	Element filtered_options
@@ -200,7 +200,6 @@ Element function get_possible_bindings(host_model : Element, schedule_model : El
 
 	Element attributes
 	String attribute
-	Element value
 	Element func
 	Boolean result
 	Element attributes_copy
@@ -545,6 +544,8 @@ Boolean function transform_forall(host_model : Element, schedule_model : Element
 	Element mapping
 	Boolean result
 
+	log("Executing rule: " + current)
+
 	mappings = full_match(host_model, schedule_model, current, False)
 
 	if (set_len(mappings) > 0):
@@ -552,7 +553,7 @@ Boolean function transform_forall(host_model : Element, schedule_model : Element
 	else:
 		result = False
 
-	//log("Matches in forall: " + cast_v2s(set_len(mappings)))
+	log("Matches in forall: " + cast_v2s(set_len(mappings)))
 	while (set_len(mappings) > 0):
 		mapping = set_pop(mappings)
 		RHS = set_pop(allAssociationDestinations(schedule_model, current, "RHSLink"))

+ 1 - 1
hybrid_server/run_mvk_server.py

@@ -2,7 +2,7 @@ import sys
 sys.path.append("../")
 
 import server
-import socket2event
+import sccd.runtime.socket2event as socket2event
 
 controller = server.Controller(sys.argv[1:])
 socket2event.boot_translation_service(controller)

+ 0 - 117
hybrid_server/socket2event.py

@@ -1,117 +0,0 @@
-import threading
-from sccd.runtime.statecharts_core import Event
-import socket
-
-send_data_queues = {}
-send_events = {}
-recv_events = {}
-run_sockets = {}
-
-def start_socket_threads(controller, sock):
-    recv_events[sock] = recv_event = threading.Event()
-    send_events[sock] = send_event = threading.Event()
-    send_data_queues[sock] = send_data_queue = []
-    run_sockets[sock] = True
-
-    thrd = threading.Thread(target=receive_from_socket, args=[controller, sock, recv_event])
-    thrd.daemon = True
-    thrd.start()
-
-    thrd = threading.Thread(target=send_to_socket, args=[controller, sock, send_data_queue, send_event])
-    thrd.daemon = True
-    thrd.start()
-
-def receive_from_socket(controller, sock, recv_event):
-    while 1:
-        recv_event.wait()
-        recv_event.clear()
-        if not run_sockets[sock]:
-            break
-        data = sock.recv(2**16)
-        controller.addInput(Event("received_socket", "socket_in", [sock, data]))
-
-def send_to_socket(controller, sock, data_queue, send_event):
-    while run_sockets[sock]:
-        send_event.wait()
-        send_event.clear()
-        while data_queue:
-            send = sock.send(data_queue.pop(0))
-            controller.addInput(Event("sent_socket", "socket_in", [sock, send]))
-        if not run_sockets[sock]:
-            break
-
-def _accept(controller, sock):
-    conn, addr = sock.accept()
-    start_socket_threads(controller, conn)
-    controller.addInput(Event("accepted_socket", "socket_in", [sock, conn]))
-
-def _connect(controller, sock, destination):
-    sock.connect(destination)
-    controller.addInput(Event("connected_socket", "socket_in", [sock]))
-
-def _close(controller, sock):
-    run_sockets[sock] = False
-    send_events[sock].set()
-    recv_events[sock].set()
-    sock.close()
-    controller.addInput(Event("closed_socket", "socket_in", [sock]))
-
-def _bind(controller, sock, addr):
-    sock.bind(addr)
-    controller.addInput(Event("bound_socket", "socket_in", [sock]))
-
-def _listen(controller, sock):
-    sock.listen(1)
-    controller.addInput(Event("listened_socket", "socket_in", [sock]))
-
-def _wrapper_func(*args):
-    func = args[0]
-    controller = args[1]
-    sock = args[2]
-    try:
-        func(*args[1:])
-    except socket.error as e:
-        print("ERROR " + str(e))
-        controller.addInput(Event("error_socket", "socket_in", [sock, e]))
-    except Exception as e:
-        print("UNKNOWN ERROR " + str(e))
-        controller.addInput(Event("unknown_error_socket", "socket_in", [sock, e]))
-
-def _start_on_daemon_thread(func, args):
-    new_args = [func]
-    new_args.extend(args)
-    args = new_args
-    thrd = threading.Thread(target=_wrapper_func, args=args)
-    thrd.daemon = True
-    thrd.start()
-
-def boot_translation_service(controller):
-    socket_out = controller.addOutputListener("socket_out")
-    _start_on_daemon_thread(_poll, [controller, socket_out])
-
-def _poll(controller, socket_out):
-    while 1:
-        evt = socket_out.fetch(-1)
-        name, params = evt.getName(), evt.getParameters()
-        if name == "accept_socket":
-            _start_on_daemon_thread(_accept, [controller, params[0]])
-        elif name == "recv_socket":
-            recv_events[params[0]].set()
-        elif name == "connect_socket":
-            _start_on_daemon_thread(_connect, [controller, params[0], params[1]])
-        elif name == "create_socket":
-            sock = socket.socket()
-            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-            start_socket_threads(controller, sock)
-            controller.addInput(Event("created_socket", "socket_in", [sock]))
-        elif name == "close_socket":
-            _start_on_daemon_thread(_close, [controller, params[0]])
-        elif name == "send_socket":
-            send_data_queues[params[0]].append(params[1])
-            send_events[params[0]].set()
-        elif name == "bind_socket":
-            _start_on_daemon_thread(_bind, [controller, params[0], params[1]])
-        elif name == "listen_socket":
-            _start_on_daemon_thread(_listen, [controller, params[0]])
-        elif name == "stop":
-            break

+ 11 - 4
integration/test_powerwindow.py

@@ -63,11 +63,12 @@ class TestPowerWindow(unittest.TestCase):
 
         global called
         called = 0
+        nr_of_operations = 6
 
         def get_function(filename):
             def func():
                 global called
-                if called > len(callbacks):
+                if called > nr_of_operations:
                     raise Exception("Seemingly called some operation twice!")
                 else:
                     called += 1
@@ -112,6 +113,7 @@ class TestPowerWindow(unittest.TestCase):
         model_add("formalisms/Query", "formalisms/SimpleClassDiagrams", open("models/query.mvc", 'r').read())
         model_add("formalisms/Architecture", "formalisms/SimpleClassDiagrams", open("models/architecture.mvc", 'r').read())
 
+        #model_add("models/pm_powerwindow", "formalisms/ProcessModel", open("models/pm_req_analyse_debug.mvc", 'r').read())
         model_add("models/pm_powerwindow", "formalisms/ProcessModel", open("models/pm_req_analyse.mvc", 'r').read())
 
         transformation_add_MANUAL({"Requirements": "formalisms/Requirements"}, {"Requirements": "formalisms/Requirements"}, "models/revise_req")
@@ -147,8 +149,12 @@ class TestPowerWindow(unittest.TestCase):
         transformation_add_AL({"ReachabilityGraph": "formalisms/ReachabilityGraph"}, {}, "models/bfs", open("models/bfs.alc", 'r').read())
         transformation_add_AL({"EPN_Plant": "formalisms/Encapsulated_PetriNet", "EPN_Control": "formalisms/Encapsulated_PetriNet", "EPN_Environment": "formalisms/Encapsulated_PetriNet"}, {"Encapsulated_PetriNet": "formalisms/Encapsulated_PetriNet"}, "models/merge_EPN", open("models/merge_EPN.alc", 'r').read())
 
+        #transformation_add_AL({"Encapsulated_PetriNet": "Encapsulated_PetriNet"}, {}, "epn_print", open("models/epn_print.alc").read())
+        #transformation_add_AL({"PetriNet": "PetriNet"}, {}, "pn_print", open("models/pn_print.alc").read())
+
         global called
         called = 0
+        executed = set([])
 
         def get_function(filename, fixed=None):
             def func():
@@ -156,10 +162,11 @@ class TestPowerWindow(unittest.TestCase):
                 if called > len(callbacks) * 2:
                     raise Exception("Seemingly called some operation twice!")
                 called += 1
-                if called > len(callbacks) and fixed is not None:
-                    model_overwrite(None, open(fixed, "r").read())
-                else:
+                if filename not in executed or fixed is None:
+                    executed.add(filename)
                     model_overwrite(None, open(filename, "r").read())
+                else:
+                    model_overwrite(None, open(fixed, "r").read())
             return func
 
         cb_req = get_function("models/requirements_model.mvc")

+ 1 - 1
integration/utils.py

@@ -77,6 +77,6 @@ def flush_data(address, data):
 
 def start_mvc():
     port = getFreePort()
-    address = "http://127.0.0.1:%s" % port
+    address = "127.0.0.1:%s" % port
     proc = execute("run_local_modelverse", [str(port)], wait=False)
     return proc, address

+ 1 - 1
interface/HUTN/grammars/actionlanguage.g

@@ -1,5 +1,5 @@
 grammar{
-    start: (include | definition | funcdecl | newline)+;
+    start: (include | definition | funcdecl | newline)*;
 
     statement 
         : (definition newline)

+ 2 - 0
interface/HUTN/grammars/modelling.g

@@ -19,6 +19,7 @@ grammar{
         | FLOAT_NUMBER
         | TRUE
         | FALSE
+        | LONG_STR
         | STRVALUE;
 
     tokens{
@@ -48,5 +49,6 @@ grammar{
         ANYTHING_EXCEPT_DOLLAR: '[^$]*';
         INCLUDE: 'include';
         EXCLAMATION: '!';
+        LONG_STR: '"""[^\"]*"""';
     }
 }

+ 3 - 0
interface/HUTN/hutn_compiler/model_visitor.py

@@ -136,6 +136,9 @@ class ModelVisitor(Visitor):
             attr_value = tree.get_children("value")[0].get_tail()[0]
             if attr_value.head == "STRVALUE":
                 attr_value = attr_value.get_text()[1:-1]
+            elif attr_value.head == "LONG_STR":
+                attr_value = attr_value.get_text()[3:-3]
+                print("Got value: " + str(attr_value))
             elif attr_value.head == "TRUE":
                 attr_value = True
             elif attr_value.head == "FALSE":

+ 6 - 0
interface/HUTN/test/modelling_language/code/multiline.mvc

@@ -0,0 +1,6 @@
+Codeblock {
+	code = """
+        def test_code(a, b):
+            return a + b
+    """
+}

+ 1 - 0
interface/HUTN/test/modelling_language/expected/multiline

@@ -0,0 +1 @@
+[7, "instantiate_node", "Codeblock", "__0", "instantiate_attribute", "__0", "code", "\n        def test_code(a, b):\n            return a + b\n    "]

+ 5 - 2
interface/HUTN/test/modelling_language/test_compile.py

@@ -8,12 +8,12 @@ def compile_file(obj, filename):
     result = main(util.get_code_path(filename), "grammars/modelling.g", "M", [])
     try:
         expected = json.loads(open(util.get_expected_path(filename)).read())
+        assert result == expected
     except:
         #f = open(util.get_expected_path(filename), 'w')
         #f.write(json.dumps(result))
         #f.close()
-        pass
-    assert result == expected
+        assert False
 
 class TestCompile(unittest.TestCase):
     def test_PetriNets(self):
@@ -27,3 +27,6 @@ class TestCompile(unittest.TestCase):
 
     def test_PetriNets_constraints(self):
         compile_file(self, "petrinets_constraints.mvc")
+
+    def test_multiline(self):
+        compile_file(self, "multiline.mvc")

+ 1 - 1
kernel/mvk_server/run_mvk_server.py

@@ -2,7 +2,7 @@ import sys
 sys.path.append("../")
 
 import server
-import socket2event
+import sccd.runtime.socket2event as socket2event
 
 #import yappi
 #yappi.start()

+ 0 - 117
kernel/mvk_server/socket2event.py

@@ -1,117 +0,0 @@
-import threading
-from python_runtime.statecharts_core import Event
-import socket
-
-send_data_queues = {}
-send_events = {}
-recv_events = {}
-run_sockets = {}
-
-def start_socket_threads(controller, sock):
-    recv_events[sock] = recv_event = threading.Event()
-    send_events[sock] = send_event = threading.Event()
-    send_data_queues[sock] = send_data_queue = []
-    run_sockets[sock] = True
-
-    thrd = threading.Thread(target=receive_from_socket, args=[controller, sock, recv_event])
-    thrd.daemon = True
-    thrd.start()
-
-    thrd = threading.Thread(target=send_to_socket, args=[controller, sock, send_data_queue, send_event])
-    thrd.daemon = True
-    thrd.start()
-
-def receive_from_socket(controller, sock, recv_event):
-    while 1:
-        recv_event.wait()
-        recv_event.clear()
-        if not run_sockets[sock]:
-            break
-        data = sock.recv(2**16)
-        controller.addInput(Event("received_socket", "socket_in", [sock, data]))
-
-def send_to_socket(controller, sock, data_queue, send_event):
-    while run_sockets[sock]:
-        send_event.wait()
-        send_event.clear()
-        while data_queue:
-            send = sock.send(data_queue.pop(0))
-            controller.addInput(Event("sent_socket", "socket_in", [sock, send]))
-        if not run_sockets[sock]:
-            break
-
-def _accept(controller, sock):
-    conn, addr = sock.accept()
-    start_socket_threads(controller, conn)
-    controller.addInput(Event("accepted_socket", "socket_in", [sock, conn]))
-
-def _connect(controller, sock, destination):
-    sock.connect(destination)
-    controller.addInput(Event("connected_socket", "socket_in", [sock]))
-
-def _close(controller, sock):
-    run_sockets[sock] = False
-    send_events[sock].set()
-    recv_events[sock].set()
-    sock.close()
-    controller.addInput(Event("closed_socket", "socket_in", [sock]))
-
-def _bind(controller, sock, addr):
-    sock.bind(addr)
-    controller.addInput(Event("bound_socket", "socket_in", [sock]))
-
-def _listen(controller, sock):
-    sock.listen(1)
-    controller.addInput(Event("listened_socket", "socket_in", [sock]))
-
-def _wrapper_func(*args):
-    func = args[0]
-    controller = args[1]
-    sock = args[2]
-    try:
-        func(*args[1:])
-    except socket.error as e:
-        print("ERROR " + str(e))
-        controller.addInput(Event("error_socket", "socket_in", [sock, e]))
-    except Exception as e:
-        print("UNKNOWN ERROR " + str(e))
-        controller.addInput(Event("unknown_error_socket", "socket_in", [sock, e]))
-
-def _start_on_daemon_thread(func, args):
-    new_args = [func]
-    new_args.extend(args)
-    args = new_args
-    thrd = threading.Thread(target=_wrapper_func, args=args)
-    thrd.daemon = True
-    thrd.start()
-
-def boot_translation_service(controller):
-    _start_on_daemon_thread(_poll, [controller, None])
-
-def _poll(controller, _):
-    socket_out = controller.addOutputListener("socket_out")
-    while 1:
-        evt = socket_out.fetch(-1)
-        name, params = evt.getName(), evt.getParameters()
-        if name == "accept_socket":
-            _start_on_daemon_thread(_accept, [controller, params[0]])
-        elif name == "recv_socket":
-            recv_events[params[0]].set()
-        elif name == "connect_socket":
-            _start_on_daemon_thread(_connect, [controller, params[0], params[1]])
-        elif name == "create_socket":
-            sock = socket.socket()
-            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-            start_socket_threads(controller, sock)
-            controller.addInput(Event("created_socket", "socket_in", [sock]))
-        elif name == "close_socket":
-            _start_on_daemon_thread(_close, [controller, params[0]])
-        elif name == "send_socket":
-            send_data_queues[params[0]].append(params[1])
-            send_events[params[0]].set()
-        elif name == "bind_socket":
-            _start_on_daemon_thread(_bind, [controller, params[0], params[1]])
-        elif name == "listen_socket":
-            _start_on_daemon_thread(_listen, [controller, params[0]])
-        elif name == "stop":
-            break

+ 8 - 8
models/SCCD_execute.alc

@@ -195,12 +195,6 @@ String function start_class(model : Element, data : Element, class : String, par
 
 	execute_actions(model, init, set_copy(class_handle["states"]), data, "")
 
-	// Notify this class itself of its ID
-	Element lst
-	lst = list_create()
-	list_append(lst, identifier)
-	set_add_node(data["current_class_handle"]["new_events"], create_tuple("instance_created", lst))
-
 	dict_overwrite(data, "current_class", prev_class)
 	dict_overwrite(data, "current_class_handle", data["classes"][prev_class])
 
@@ -756,7 +750,14 @@ Boolean function main(model : Element):
 	default_class = set_pop(filter(model, allInstances(model, "SCCD/Class"), "default", True))
 
 	// Start up the default class
-	start_class(model, data, default_class, read_root())
+	String identifier
+	identifier = start_class(model, data, default_class, read_root())
+
+	// Notify this class itself of its ID
+	Element lst
+	lst = list_create()
+	list_append(lst, identifier)
+	set_add_node(data["current_class_handle"]["new_events"], create_tuple("instance_created", lst))
 
 	Float timeout
 	Element interrupt
@@ -777,7 +778,6 @@ Boolean function main(model : Element):
 			// Update the simulated time to the time of interrupt
 			time_sim = time() - time_0
 
-		dict_overwrite(data, "new_events", set_create())
 		Element classes
 		classes = dict_keys(data["classes"])
 		while(set_len(classes) > 0):

+ 1 - 0
models/merge_EPN.alc

@@ -12,4 +12,5 @@ Boolean function main(model : Element):
 		split = string_split(read_type(model, key), "/")
 		retype(model, key, string_join("Encapsulated_PetriNet/", split[1]))
 
+	//log("merge_EPN has seen # elements: " + cast_v2s(dict_len(model["model"])))
 	return True!

+ 1 - 5
models/pm_req_analyse_debug.mvc

@@ -108,10 +108,6 @@ Data environment_EPN {
     name = "models/environment_EPN"
     type = "formalisms/Encapsulated_PetriNet"
 }
-Data merged_EPN {
-    name = "models/merged_EPN"
-    type = "formalisms/Encapsulated_PetriNet"
-}
 Data pn {
     name = "models/pn"
     type = "formalisms/PetriNet"
@@ -310,5 +306,5 @@ Consumes (print_control_EPN, control_EPN){
     name = "Encapsulated_PetriNet"
 }
 Consumes (print_env_EPN, environment_EPN){
-    name = "PW_Environment"
+    name = "Encapsulated_PetriNet"
 }

+ 29 - 17
scripts/HUTN_service.py

@@ -7,39 +7,47 @@ from hutn_compiler.compiler import main as do_compile
 from modelverse import *
 import os
 
-init()
+import time
+time.sleep(1)
+init(sys.argv[1])
 login("HUTN", "HUTN")
 
+def clean_code(code):
+    if code == "":
+        return code
+
+    code_fragments = code.split("\n")
+    code_fragments = [i.rstrip() 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)
+    return code
+
 def compile_service(port):
     start = time.time()
     temp_file = ".tmp_%s" % port
+
     def compile_AL(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)
+        code = clean_code(code)
+
+        if code == "":
+            return [0]
 
         with open(temp_file, "w") as f:
             f.write(code)
             f.flush()
 
-        ss = time.time()
         compiled = do_compile(temp_file, COMPILER_PATH + "/grammars/actionlanguage.g", "CS")
-        print("    Compile: %ss" % (time.time() - ss))
         os.remove(temp_file)
         return compiled
 
     def compile_model(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)
+        code = clean_code(code)
+
+        if code == "":
+            return [0]
 
         with open(temp_file, "w") as f:
             f.write(code)
@@ -72,5 +80,9 @@ service_register("compiler", compile_service)
 try:
     while raw_input() != "STOP":
         pass
+except EOFError:
+    import time
+    while 1:
+        time.sleep(1.0)
 finally:
     service_stop()

+ 1 - 1
scripts/run_basic_tests.py

@@ -13,4 +13,4 @@ subprocess.check_call([sys.executable, "-m", "pytest"], cwd="kernel")
 
 subprocess.check_call([sys.executable, "-m", "pytest"], cwd="interface/HUTN")
 
-subprocess.check_call([sys.executable, "-m", "pytest", "unit", "-x", "-v"])
+subprocess.check_call([sys.executable, "-m", "pytest", "unit", "-x", "-v", "-s"])

+ 22 - 11
scripts/run_local_modelverse.py

@@ -8,17 +8,28 @@ if len(sys.argv) < 2:
 else:
     port = sys.argv[1]
 
-os.chdir("hybrid_server")
-subprocess.check_call([sys.executable, "-m", "sccd.compiler.sccdc", "-p", "threads", "server.xml"])
+# Start up the HUTN compilation service already
+try:
+    hutn = subprocess.Popen([sys.executable, "scripts/HUTN_service.py", "127.0.0.1:%s" % port])
 
-program_to_execute = [sys.executable, "run_mvk_server.py", port]
+    os.chdir("hybrid_server")
+    subprocess.check_call([sys.executable, "-m", "sccd.compiler.sccdc", "-p", "threads", "server.xml"])
 
-# Alternative execution modes
-#program_to_execute = [sys.executable, "-m", "cProfile", "-s", "tottime", "run_mvk_server.py", port]
-#program_to_execute = [sys.executable, "run_mvk_server.py", port, "--kernel=interpreter"]
-#program_to_execute = [sys.executable, "run_mvk_server.py", port, "--kernel=fast-jit"]
+    program_to_execute = [sys.executable, "run_mvk_server.py", port]
 
-if os.name == "nt":
-    subprocess.call(program_to_execute)
-else:
-    os.execv(sys.executable, program_to_execute)
+    # Alternative execution modes
+    #program_to_execute = [sys.executable, "-m", "cProfile", "-s", "tottime", "run_mvk_server.py", port]
+    #program_to_execute = [sys.executable, "run_mvk_server.py", port, "--kernel=interpreter"]
+    #program_to_execute = [sys.executable, "run_mvk_server.py", port, "--kernel=fast-jit"]
+
+    server = subprocess.Popen(program_to_execute)
+    server.wait()
+finally:
+    try:
+        server.terminate()
+    except:
+        pass
+    try:
+        hutn.terminate()
+    except:
+        pass

+ 1 - 1
state/mvs_server/run_mvs_server.py

@@ -2,7 +2,7 @@ import sys
 sys.path.append("../")
 
 import server
-import socket2event
+import sccd.runtime.socket2event as socket2event
 
 controller = server.Controller(sys.argv[1])
 socket2event.boot_translation_service(controller)

+ 0 - 117
state/mvs_server/socket2event.py

@@ -1,117 +0,0 @@
-import threading
-from python_runtime.statecharts_core import Event
-import socket
-
-send_data_queues = {}
-send_events = {}
-recv_events = {}
-run_sockets = {}
-
-def start_socket_threads(controller, sock):
-    recv_events[sock] = recv_event = threading.Event()
-    send_events[sock] = send_event = threading.Event()
-    send_data_queues[sock] = send_data_queue = []
-    run_sockets[sock] = True
-
-    thrd = threading.Thread(target=receive_from_socket, args=[controller, sock, recv_event])
-    thrd.daemon = True
-    thrd.start()
-
-    thrd = threading.Thread(target=send_to_socket, args=[controller, sock, send_data_queue, send_event])
-    thrd.daemon = True
-    thrd.start()
-
-def receive_from_socket(controller, sock, recv_event):
-    while 1:
-        recv_event.wait()
-        recv_event.clear()
-        if not run_sockets[sock]:
-            break
-        data = sock.recv(2**16)
-        controller.addInput(Event("received_socket", "socket_in", [sock, data]))
-
-def send_to_socket(controller, sock, data_queue, send_event):
-    while run_sockets[sock]:
-        send_event.wait()
-        send_event.clear()
-        while data_queue:
-            send = sock.send(data_queue.pop(0))
-            controller.addInput(Event("sent_socket", "socket_in", [sock, send]))
-        if not run_sockets[sock]:
-            break
-
-def _accept(controller, sock):
-    conn, addr = sock.accept()
-    start_socket_threads(controller, conn)
-    controller.addInput(Event("accepted_socket", "socket_in", [sock, conn]))
-
-def _connect(controller, sock, destination):
-    sock.connect(destination)
-    controller.addInput(Event("connected_socket", "socket_in", [sock]))
-
-def _close(controller, sock):
-    run_sockets[sock] = False
-    send_events[sock].set()
-    recv_events[sock].set()
-    sock.close()
-    controller.addInput(Event("closed_socket", "socket_in", [sock]))
-
-def _bind(controller, sock, addr):
-    sock.bind(addr)
-    controller.addInput(Event("bound_socket", "socket_in", [sock]))
-
-def _listen(controller, sock):
-    sock.listen(1)
-    controller.addInput(Event("listened_socket", "socket_in", [sock]))
-
-def _wrapper_func(*args):
-    func = args[0]
-    controller = args[1]
-    sock = args[2]
-    try:
-        func(*args[1:])
-    except socket.error as e:
-        print("ERROR " + str(e))
-        controller.addInput(Event("error_socket", "socket_in", [sock, e]))
-    except Exception as e:
-        print("UNKNOWN ERROR " + str(e))
-        controller.addInput(Event("unknown_error_socket", "socket_in", [sock, e]))
-
-def _start_on_daemon_thread(func, args):
-    new_args = [func]
-    new_args.extend(args)
-    args = new_args
-    thrd = threading.Thread(target=_wrapper_func, args=args)
-    thrd.daemon = True
-    thrd.start()
-
-def boot_translation_service(controller):
-    _start_on_daemon_thread(_poll, [controller, None])
-
-def _poll(controller, _):
-    socket_out = controller.addOutputListener("socket_out")
-    while 1:
-        evt = socket_out.fetch(-1)
-        name, params = evt.getName(), evt.getParameters()
-        if name == "accept_socket":
-            _start_on_daemon_thread(_accept, [controller, params[0]])
-        elif name == "recv_socket":
-            recv_events[params[0]].set()
-        elif name == "connect_socket":
-            _start_on_daemon_thread(_connect, [controller, params[0], params[1]])
-        elif name == "create_socket":
-            sock = socket.socket()
-            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-            start_socket_threads(controller, sock)
-            controller.addInput(Event("created_socket", "socket_in", [sock]))
-        elif name == "close_socket":
-            _start_on_daemon_thread(_close, [controller, params[0]])
-        elif name == "send_socket":
-            send_data_queues[params[0]].append(params[1])
-            send_events[params[0]].set()
-        elif name == "bind_socket":
-            _start_on_daemon_thread(_bind, [controller, params[0], params[1]])
-        elif name == "listen_socket":
-            _start_on_daemon_thread(_listen, [controller, params[0]])
-        elif name == "stop":
-            break

+ 106 - 0
unit/log_output.py

@@ -0,0 +1,106 @@
+"""
+Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)
+
+Date:   Mon Aug 28 10:53:51 2017
+
+Model author: Yentl Van Tendeloo
+Model name:   Logging
+Model description:
+For testing: append all input to a log until finished
+"""
+
+from sccd.runtime.statecharts_core import *
+
+# package "Logging"
+
+class Logging(RuntimeClassBase):
+    def __init__(self, controller, log):
+        RuntimeClassBase.__init__(self, controller)
+        
+        self.semantics.big_step_maximality = StatechartSemantics.TakeMany
+        self.semantics.internal_event_lifeline = StatechartSemantics.Queue
+        self.semantics.input_event_lifeline = StatechartSemantics.FirstComboStep
+        self.semantics.priority = StatechartSemantics.SourceParent
+        self.semantics.concurrency = StatechartSemantics.Single
+        
+        # build Statechart structure
+        self.build_statechart_structure()
+        
+        # call user defined constructor
+        Logging.user_defined_constructor(self, log)
+    
+    def user_defined_constructor(self, log):
+        self.log = log
+    
+    def user_defined_destructor(self):
+        pass
+    
+    
+    # builds Statechart structure
+    def build_statechart_structure(self):
+        
+        # state <root>
+        self.states[""] = State(0, "", self)
+        
+        # state /init
+        self.states["/init"] = State(1, "/init", self)
+        self.states["/init"].setEnter(self._init_enter)
+        self.states["/init"].setExit(self._init_exit)
+        
+        # state /finished
+        self.states["/finished"] = State(2, "/finished", self)
+        
+        # add children
+        self.states[""].addChild(self.states["/init"])
+        self.states[""].addChild(self.states["/finished"])
+        self.states[""].fixTree()
+        self.states[""].default_state = self.states["/init"]
+        
+        # transition /init
+        _init_0 = Transition(self, self.states["/init"], [self.states["/init"]])
+        _init_0.setAction(self._init_0_exec)
+        _init_0.setTrigger(Event("input", "inp"))
+        self.states["/init"].addTransition(_init_0)
+        _init_1 = Transition(self, self.states["/init"], [self.states["/init"]])
+        _init_1.setTrigger(Event("_0after"))
+        self.states["/init"].addTransition(_init_1)
+        _init_2 = Transition(self, self.states["/init"], [self.states["/finished"]])
+        _init_2.setTrigger(Event("terminate", "inp"))
+        self.states["/init"].addTransition(_init_2)
+    
+    def _init_enter(self):
+        self.addTimer(0, 0.1)
+    
+    def _init_exit(self):
+        self.removeTimer(0)
+    
+    def _init_0_exec(self, parameters):
+        value = parameters[0]
+        self.log.append(value)
+        print("Got value: " + str(value))
+    
+    def initializeStatechart(self):
+        # enter default state
+        self.default_targets = self.states["/init"].getEffectiveTargetStates()
+        RuntimeClassBase.initializeStatechart(self)
+
+class ObjectManager(ObjectManagerBase):
+    def __init__(self, controller):
+        ObjectManagerBase.__init__(self, controller)
+    
+    def instantiate(self, class_name, construct_params):
+        if class_name == "Logging":
+            instance = Logging(self.controller, construct_params[0])
+            instance.associations = {}
+        else:
+            raise Exception("Cannot instantiate class " + class_name)
+        return instance
+
+class Controller(ThreadsControllerBase):
+    def __init__(self, log, keep_running = None, behind_schedule_callback = None):
+        if keep_running == None: keep_running = True
+        if behind_schedule_callback == None: behind_schedule_callback = None
+        ThreadsControllerBase.__init__(self, ObjectManager(self), keep_running, behind_schedule_callback)
+        self.addInputPort("inp")
+        self.addOutputPort("outp")
+        self.object_manager.createInstance("Logging", [log])

+ 39 - 0
unit/log_output.xml

@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<diagram author="Yentl Van Tendeloo" name="Logging">
+    <description>
+        For testing: append all input to a log until finished
+    </description>
+
+    <inport name="inp"/>
+    <outport name="outp"/>
+
+    <class name="Logging" default="true">
+        <constructor>
+            <parameter name="log"/>
+            <body>
+                self.log = log
+            </body>
+        </constructor>
+        <scxml initial="init">
+            <state id="init">
+                <transition event="input" port="inp" target=".">
+                    <parameter name="value"/>
+                    <script>
+                        self.log.append(value)
+                        print("Got value: " + str(value))
+                    </script>
+                </transition>
+
+                <transition after="0.1" target="."/>
+
+                <transition event="terminate" port="inp" target="../finished"/>
+            </state>
+
+            <state id="finished">
+                <script>
+                    print("FINISHED")
+                </script>
+            </state>
+        </scxml>
+    </class>
+</diagram>

+ 15 - 2
unit/test_all.py

@@ -209,8 +209,15 @@ class TestModelverse(unittest.TestCase):
         transformation_add_AL({"PetriNet_Runtime": "test/PetriNet_Runtime"}, {"PetriNet_Runtime": "test/PetriNet_Runtime"}, "test/pn_simulate", open("integration/code/pn_simulate.alc").read())
         transformation_add_MT({"PetriNet_Runtime": "test/PetriNet_Runtime"}, {"PetriNet": "test/PetriNet"}, "test/pn_runtime_to_design", open("integration/code/pn_runtime_to_design.mvc").read(), add_tracability_R2D)
 
+        import log_output
         log = []
-        assert transformation_execute_MT("test/print_pn", {"PetriNet": "test/my_pn"}, {}, callback) == True
+        ctrl = log_output.Controller(log, keep_running=False)
+        thrd = threading.Thread(target=ctrl.start)
+        thrd.daemon = True
+        thrd.start()
+
+        assert transformation_execute_MT("test/print_pn", {"PetriNet": "test/my_pn"}, {}, (ctrl, "inp", "outp")) == None
+        thrd.join()
         assert set(log) == set(['"p1" --> 1',
                                 '"p2" --> 2',
                                 '"p3" --> 3'])
@@ -220,7 +227,13 @@ class TestModelverse(unittest.TestCase):
         assert transformation_execute_MT("test/pn_runtime_to_design", {"PetriNet_Runtime": "test/my_pn_RT"}, {"PetriNet": "test/my_pn"}) == True
 
         log = []
-        assert transformation_execute_MT("test/print_pn", {"PetriNet": "test/my_pn"}, {}, callback) == True
+        ctrl = log_output.Controller(log, keep_running=False)
+        thrd = threading.Thread(target=ctrl.start)
+        thrd.daemon = True
+        thrd.start()
+
+        assert transformation_execute_MT("test/print_pn", {"PetriNet": "test/my_pn"}, {}, (ctrl, "inp", "outp")) == None
+        thrd.join()
         assert set(log) == set(['"p1" --> 0',
                                 '"p2" --> 1',
                                 '"p3" --> 5'])

+ 1 - 1
unit/utils.py

@@ -77,6 +77,6 @@ def flush_data(address, data):
 
 def start_mvc():
     port = getFreePort()
-    address = "http://127.0.0.1:%s" % port
+    address = "127.0.0.1:%s" % port
     proc = execute("run_local_modelverse", [str(port)], wait=False)
     return proc, address

+ 371 - 0
wrappers/http_client.py

@@ -0,0 +1,371 @@
+"""
+Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)
+
+Date:   Fri Aug 25 15:48:04 2017
+
+Model author: Yentl Van Tendeloo
+Model name:   HTTP client
+Model description:
+HTTP client.
+"""
+
+from sccd.runtime.statecharts_core import *
+import uuid
+
+# package "HTTP client"
+
+class HTTPClient(RuntimeClassBase):
+    def __init__(self, controller):
+        RuntimeClassBase.__init__(self, controller)
+        
+        self.semantics.big_step_maximality = StatechartSemantics.TakeMany
+        self.semantics.internal_event_lifeline = StatechartSemantics.Queue
+        self.semantics.input_event_lifeline = StatechartSemantics.FirstComboStep
+        self.semantics.priority = StatechartSemantics.SourceParent
+        self.semantics.concurrency = StatechartSemantics.Single
+        
+        # build Statechart structure
+        self.build_statechart_structure()
+        
+        # call user defined constructor
+        HTTPClient.user_defined_constructor(self)
+    
+    def user_defined_constructor(self):
+        self.socket = None
+        self.received_data = ""
+        self.send_data = ""
+        self.queue = []
+        self.IDs = []
+    
+    def user_defined_destructor(self):
+        pass
+    
+    
+    # builds Statechart structure
+    def build_statechart_structure(self):
+        
+        # state <root>
+        self.states[""] = State(0, "", self)
+        
+        # state /init
+        self.states["/init"] = State(1, "/init", self)
+        self.states["/init"].setEnter(self._init_enter)
+        
+        # state /waiting
+        self.states["/waiting"] = State(2, "/waiting", self)
+        self.states["/waiting"].setEnter(self._waiting_enter)
+        
+        # state /connecting
+        self.states["/connecting"] = State(3, "/connecting", self)
+        self.states["/connecting"].setEnter(self._connecting_enter)
+        self.states["/connecting"].setExit(self._connecting_exit)
+        
+        # state /connecting/connecting
+        self.states["/connecting/connecting"] = State(4, "/connecting/connecting", self)
+        self.states["/connecting/connecting"].setEnter(self._connecting_connecting_enter)
+        
+        # state /connecting/cooldown
+        self.states["/connecting/cooldown"] = State(5, "/connecting/cooldown", self)
+        self.states["/connecting/cooldown"].setEnter(self._connecting_cooldown_enter)
+        self.states["/connecting/cooldown"].setExit(self._connecting_cooldown_exit)
+        
+        # state /connected
+        self.states["/connected"] = ParallelState(6, "/connected", self)
+        
+        # state /connected/listening
+        self.states["/connected/listening"] = State(7, "/connected/listening", self)
+        
+        # state /connected/listening/listen
+        self.states["/connected/listening/listen"] = State(8, "/connected/listening/listen", self)
+        self.states["/connected/listening/listen"].setEnter(self._connected_listening_listen_enter)
+        
+        # state /connected/listening/close
+        self.states["/connected/listening/close"] = State(9, "/connected/listening/close", self)
+        
+        # state /connected/sending
+        self.states["/connected/sending"] = State(10, "/connected/sending", self)
+        
+        # state /connected/sending/waiting_for_data
+        self.states["/connected/sending/waiting_for_data"] = State(11, "/connected/sending/waiting_for_data", self)
+        
+        # state /connected/sending/transferring
+        self.states["/connected/sending/transferring"] = State(12, "/connected/sending/transferring", self)
+        
+        # state /connected/queueing
+        self.states["/connected/queueing"] = State(13, "/connected/queueing", self)
+        
+        # state /connected/queueing/queueing
+        self.states["/connected/queueing/queueing"] = State(14, "/connected/queueing/queueing", self)
+        self.states["/connected/queueing/queueing"].setEnter(self._connected_queueing_queueing_enter)
+        
+        # state /connected/parsing
+        self.states["/connected/parsing"] = State(15, "/connected/parsing", self)
+        
+        # state /connected/parsing/wait_for_header
+        self.states["/connected/parsing/wait_for_header"] = State(16, "/connected/parsing/wait_for_header", self)
+        
+        # state /connected/parsing/wait_for_payload
+        self.states["/connected/parsing/wait_for_payload"] = State(17, "/connected/parsing/wait_for_payload", self)
+        
+        # add children
+        self.states[""].addChild(self.states["/init"])
+        self.states[""].addChild(self.states["/waiting"])
+        self.states[""].addChild(self.states["/connecting"])
+        self.states[""].addChild(self.states["/connected"])
+        self.states["/connecting"].addChild(self.states["/connecting/connecting"])
+        self.states["/connecting"].addChild(self.states["/connecting/cooldown"])
+        self.states["/connected"].addChild(self.states["/connected/listening"])
+        self.states["/connected"].addChild(self.states["/connected/sending"])
+        self.states["/connected"].addChild(self.states["/connected/queueing"])
+        self.states["/connected"].addChild(self.states["/connected/parsing"])
+        self.states["/connected/listening"].addChild(self.states["/connected/listening/listen"])
+        self.states["/connected/listening"].addChild(self.states["/connected/listening/close"])
+        self.states["/connected/sending"].addChild(self.states["/connected/sending/waiting_for_data"])
+        self.states["/connected/sending"].addChild(self.states["/connected/sending/transferring"])
+        self.states["/connected/queueing"].addChild(self.states["/connected/queueing/queueing"])
+        self.states["/connected/parsing"].addChild(self.states["/connected/parsing/wait_for_header"])
+        self.states["/connected/parsing"].addChild(self.states["/connected/parsing/wait_for_payload"])
+        self.states[""].fixTree()
+        self.states[""].default_state = self.states["/init"]
+        self.states["/connecting"].default_state = self.states["/connecting/connecting"]
+        self.states["/connected/listening"].default_state = self.states["/connected/listening/listen"]
+        self.states["/connected/sending"].default_state = self.states["/connected/sending/waiting_for_data"]
+        self.states["/connected/queueing"].default_state = self.states["/connected/queueing/queueing"]
+        self.states["/connected/parsing"].default_state = self.states["/connected/parsing/wait_for_header"]
+        
+        # transition /init
+        _init_0 = Transition(self, self.states["/init"], [self.states["/waiting"]])
+        _init_0.setAction(self._init_0_exec)
+        _init_0.setTrigger(Event("created_socket", "socket_in"))
+        _init_0.setGuard(self._init_0_guard)
+        self.states["/init"].addTransition(_init_0)
+        
+        # transition /waiting
+        _waiting_0 = Transition(self, self.states["/waiting"], [self.states["/connecting"]])
+        _waiting_0.setAction(self._waiting_0_exec)
+        _waiting_0.setTrigger(Event("connect", "request_in"))
+        self.states["/waiting"].addTransition(_waiting_0)
+        
+        # transition /connecting/connecting
+        _connecting_connecting_0 = Transition(self, self.states["/connecting/connecting"], [self.states["/connecting/cooldown"]])
+        _connecting_connecting_0.setTrigger(Event("error_socket", "socket_in"))
+        self.states["/connecting/connecting"].addTransition(_connecting_connecting_0)
+        _connecting_connecting_1 = Transition(self, self.states["/connecting/connecting"], [self.states["/connected"]])
+        _connecting_connecting_1.setAction(self._connecting_connecting_1_exec)
+        _connecting_connecting_1.setTrigger(Event("connected_socket", "socket_in"))
+        _connecting_connecting_1.setGuard(self._connecting_connecting_1_guard)
+        self.states["/connecting/connecting"].addTransition(_connecting_connecting_1)
+        
+        # transition /connecting/cooldown
+        _connecting_cooldown_0 = Transition(self, self.states["/connecting/cooldown"], [self.states["/connecting/connecting"]])
+        _connecting_cooldown_0.setTrigger(Event("_1after"))
+        self.states["/connecting/cooldown"].addTransition(_connecting_cooldown_0)
+        
+        # transition /connected/listening/listen
+        _connected_listening_listen_0 = Transition(self, self.states["/connected/listening/listen"], [self.states["/connected/listening/listen"]])
+        _connected_listening_listen_0.setAction(self._connected_listening_listen_0_exec)
+        _connected_listening_listen_0.setTrigger(Event("received_socket", "socket_in"))
+        _connected_listening_listen_0.setGuard(self._connected_listening_listen_0_guard)
+        self.states["/connected/listening/listen"].addTransition(_connected_listening_listen_0)
+        _connected_listening_listen_1 = Transition(self, self.states["/connected/listening/listen"], [self.states["/connected/listening/close"]])
+        _connected_listening_listen_1.setTrigger(Event("received_socket", "socket_in"))
+        _connected_listening_listen_1.setGuard(self._connected_listening_listen_1_guard)
+        self.states["/connected/listening/listen"].addTransition(_connected_listening_listen_1)
+        
+        # transition /connected/sending/waiting_for_data
+        _connected_sending_waiting_for_data_0 = Transition(self, self.states["/connected/sending/waiting_for_data"], [self.states["/connected/sending/transferring"]])
+        _connected_sending_waiting_for_data_0.setAction(self._connected_sending_waiting_for_data_0_exec)
+        _connected_sending_waiting_for_data_0.setTrigger(None)
+        _connected_sending_waiting_for_data_0.setGuard(self._connected_sending_waiting_for_data_0_guard)
+        self.states["/connected/sending/waiting_for_data"].addTransition(_connected_sending_waiting_for_data_0)
+        
+        # transition /connected/sending/transferring
+        _connected_sending_transferring_0 = Transition(self, self.states["/connected/sending/transferring"], [self.states["/connected/sending/waiting_for_data"]])
+        _connected_sending_transferring_0.setAction(self._connected_sending_transferring_0_exec)
+        _connected_sending_transferring_0.setTrigger(Event("sent_socket", "socket_in"))
+        _connected_sending_transferring_0.setGuard(self._connected_sending_transferring_0_guard)
+        self.states["/connected/sending/transferring"].addTransition(_connected_sending_transferring_0)
+        
+        # transition /connected/queueing/queueing
+        _connected_queueing_queueing_0 = Transition(self, self.states["/connected/queueing/queueing"], [self.states["/connected/queueing/queueing"]])
+        _connected_queueing_queueing_0.setAction(self._connected_queueing_queueing_0_exec)
+        _connected_queueing_queueing_0.setTrigger(Event("HTTP_input", "request_in"))
+        self.states["/connected/queueing/queueing"].addTransition(_connected_queueing_queueing_0)
+        
+        # transition /connected/parsing/wait_for_header
+        _connected_parsing_wait_for_header_0 = Transition(self, self.states["/connected/parsing/wait_for_header"], [self.states["/connected/parsing/wait_for_payload"]])
+        _connected_parsing_wait_for_header_0.setAction(self._connected_parsing_wait_for_header_0_exec)
+        _connected_parsing_wait_for_header_0.setTrigger(None)
+        _connected_parsing_wait_for_header_0.setGuard(self._connected_parsing_wait_for_header_0_guard)
+        self.states["/connected/parsing/wait_for_header"].addTransition(_connected_parsing_wait_for_header_0)
+        
+        # transition /connected/parsing/wait_for_payload
+        _connected_parsing_wait_for_payload_0 = Transition(self, self.states["/connected/parsing/wait_for_payload"], [self.states["/connected/parsing/wait_for_header"]])
+        _connected_parsing_wait_for_payload_0.setAction(self._connected_parsing_wait_for_payload_0_exec)
+        _connected_parsing_wait_for_payload_0.setTrigger(None)
+        _connected_parsing_wait_for_payload_0.setGuard(self._connected_parsing_wait_for_payload_0_guard)
+        self.states["/connected/parsing/wait_for_payload"].addTransition(_connected_parsing_wait_for_payload_0)
+        _connected_parsing_wait_for_payload_1 = Transition(self, self.states["/connected/parsing/wait_for_payload"], [self.states["/connected/parsing/wait_for_header"]])
+        _connected_parsing_wait_for_payload_1.setAction(self._connected_parsing_wait_for_payload_1_exec)
+        _connected_parsing_wait_for_payload_1.setTrigger(None)
+        _connected_parsing_wait_for_payload_1.setGuard(self._connected_parsing_wait_for_payload_1_guard)
+        self.states["/connected/parsing/wait_for_payload"].addTransition(_connected_parsing_wait_for_payload_1)
+        
+        # transition /connecting
+        _connecting_0 = Transition(self, self.states["/connecting"], [self.states["/waiting"]])
+        _connecting_0.setAction(self._connecting_0_exec)
+        _connecting_0.setTrigger(Event("_0after"))
+        self.states["/connecting"].addTransition(_connecting_0)
+    
+    def _connecting_enter(self):
+        self.addTimer(0, self.timeout)
+    
+    def _connecting_exit(self):
+        self.removeTimer(0)
+    
+    def _init_enter(self):
+        self.ID = str(uuid.uuid4())
+        self.big_step.outputEvent(Event("create_socket", "socket_out", [self.ID]))
+    
+    def _waiting_enter(self):
+        self.big_step.outputEvent(Event("http_client_initialized", "request_out", []))
+    
+    def _connecting_connecting_enter(self):
+        self.big_step.outputEvent(Event("connect_socket", "socket_out", [self.socket, self.address]))
+    
+    def _connecting_cooldown_enter(self):
+        self.addTimer(1, 0.1)
+    
+    def _connecting_cooldown_exit(self):
+        self.removeTimer(1)
+    
+    def _connected_listening_listen_enter(self):
+        self.big_step.outputEvent(Event("recv_socket", "socket_out", [self.socket]))
+    
+    def _connected_queueing_queueing_enter(self):
+        pass
+    
+    def _connecting_0_exec(self, parameters):
+        self.big_step.outputEvent(Event("http_client_timeout", "request_out", []))
+    
+    def _init_0_exec(self, parameters):
+        socket = parameters[0]
+        ID = parameters[1]
+        self.socket = socket
+    
+    def _init_0_guard(self, parameters):
+        socket = parameters[0]
+        ID = parameters[1]
+        return self.ID == ID
+    
+    def _waiting_0_exec(self, parameters):
+        address = parameters[0]
+        timeout = parameters[1]
+        self.address = address
+        self.timeout = timeout
+    
+    def _connecting_connecting_1_exec(self, parameters):
+        socket = parameters[0]
+        self.big_step.outputEvent(Event("http_client_ready", "request_out", []))
+    
+    def _connecting_connecting_1_guard(self, parameters):
+        socket = parameters[0]
+        return self.socket == socket
+    
+    def _connected_listening_listen_0_exec(self, parameters):
+        socket = parameters[0]
+        data = parameters[1]
+        self.received_data += data
+    
+    def _connected_listening_listen_0_guard(self, parameters):
+        socket = parameters[0]
+        data = parameters[1]
+        return (self.socket == socket) and (len(data) > 0)
+    
+    def _connected_listening_listen_1_guard(self, parameters):
+        socket = parameters[0]
+        data = parameters[1]
+        return (self.socket == socket) and (len(data) == 0)
+    
+    def _connected_sending_waiting_for_data_0_exec(self, parameters):
+        self.big_step.outputEvent(Event("send_socket", "socket_out", [self.socket, self.send_data]))
+    
+    def _connected_sending_waiting_for_data_0_guard(self, parameters):
+        return len(self.send_data) > 0
+    
+    def _connected_sending_transferring_0_exec(self, parameters):
+        socket = parameters[0]
+        sent_bytes = parameters[1]
+        self.send_data = self.send_data[sent_bytes:]
+    
+    def _connected_sending_transferring_0_guard(self, parameters):
+        socket = parameters[0]
+        sent_bytes = parameters[1]
+        return self.socket == socket
+    
+    def _connected_queueing_queueing_0_exec(self, parameters):
+        data = parameters[0]
+        ID = parameters[1]
+        self.send_data += "POST / HTTP/1.0\r\n"
+        self.send_data += "Content-Length: %i\r\n" % len(str(data))
+        self.send_data += "\r\n"
+        self.send_data += data
+        self.IDs.append(ID)
+    
+    def _connected_parsing_wait_for_header_0_exec(self, parameters):
+        header, self.received_data = self.received_data.split("\r\n\r\n", 1)
+        header = header.lower()
+        if "content-length" in header:
+            _, after = header.split("content-length:", 1)
+            after, _ = after.split("\r\n", 1)
+            after = after.strip()
+            self.length = int(after)
+        else:
+            self.length = float('inf')
+    
+    def _connected_parsing_wait_for_header_0_guard(self, parameters):
+        return '\r\n\r\n' in self.received_data
+    
+    def _connected_parsing_wait_for_payload_0_exec(self, parameters):
+        data = self.received_data[:self.length]
+        self.received_data = self.received_data[self.length:]
+        self.big_step.outputEvent(Event("HTTP_output", "request_out", [data, self.IDs.pop(0)]))
+    
+    def _connected_parsing_wait_for_payload_0_guard(self, parameters):
+        return len(self.received_data) >= self.length and self.IDs[0] is not None
+    
+    def _connected_parsing_wait_for_payload_1_exec(self, parameters):
+        # Drop data
+        self.received_data = self.received_data[self.length:]
+        self.IDs.pop(0)
+    
+    def _connected_parsing_wait_for_payload_1_guard(self, parameters):
+        return len(self.received_data) >= self.length and self.IDs[0] is None
+    
+    def initializeStatechart(self):
+        # enter default state
+        self.default_targets = self.states["/init"].getEffectiveTargetStates()
+        RuntimeClassBase.initializeStatechart(self)
+
+class ObjectManager(ObjectManagerBase):
+    def __init__(self, controller):
+        ObjectManagerBase.__init__(self, controller)
+    
+    def instantiate(self, class_name, construct_params):
+        if class_name == "HTTPClient":
+            instance = HTTPClient(self.controller)
+            instance.associations = {}
+        else:
+            raise Exception("Cannot instantiate class " + class_name)
+        return instance
+
+class Controller(ThreadsControllerBase):
+    def __init__(self, keep_running = None, behind_schedule_callback = None):
+        if keep_running == None: keep_running = True
+        if behind_schedule_callback == None: behind_schedule_callback = None
+        ThreadsControllerBase.__init__(self, ObjectManager(self), keep_running, behind_schedule_callback)
+        self.addInputPort("socket_in")
+        self.addInputPort("request_in")
+        self.addOutputPort("socket_out")
+        self.addOutputPort("request_out")
+        self.object_manager.createInstance("HTTPClient", [])

+ 192 - 0
wrappers/http_client.xml

@@ -0,0 +1,192 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<diagram author="Yentl Van Tendeloo" name="HTTP client">
+    <description>
+        HTTP client.
+    </description>
+    <top>
+        import uuid
+    </top>
+
+    <inport name="socket_in"/>
+    <outport name="socket_out"/>
+
+    <inport name="request_in"/>
+    <outport name="request_out"/>
+
+    <class name="HTTPClient">
+        <constructor>
+            <body>
+                <![CDATA[
+                self.socket = None
+                self.received_data = ""
+                self.send_data = ""
+                self.queue = []
+                self.IDs = []
+                ]]>
+            </body>
+        </constructor>
+        <scxml initial="init">
+            <state id="init">
+                <onentry>
+                    <script>
+                        self.ID = str(uuid.uuid4())
+                    </script>
+                    <raise scope="output" event="create_socket" port="socket_out">
+                        <parameter expr="self.ID"/>
+                    </raise>
+                </onentry>
+
+                <transition port="socket_in" event="created_socket" cond="self.ID == ID" target="../waiting">
+                    <parameter name="socket"/>
+                    <parameter name="ID"/>
+                    <script>
+                        self.socket = socket
+                    </script>
+                </transition>
+            </state>
+
+            <state id="waiting">
+                <onentry>
+                    <raise scope="output" port="request_out" event="http_client_initialized"/>
+                </onentry>
+
+                <transition port="request_in" event="connect" target="../connecting">
+                    <parameter name="address"/>
+                    <parameter name="timeout"/>
+
+                    <script>
+                        self.address = address
+                        self.timeout = timeout
+                    </script>
+                </transition>
+            </state>
+
+            <state id="connecting" initial="connecting">
+                <state id="connecting">
+                    <onentry>
+                        <raise scope="output" event="connect_socket" port="socket_out">
+                            <parameter expr="self.socket"/>
+                            <parameter expr="self.address"/>
+                        </raise>
+                    </onentry>
+
+                    <transition port="socket_in" event="error_socket" target="../cooldown"/>
+
+                    <transition port="socket_in" event="connected_socket" cond="self.socket == socket" target="../../connected">
+                        <parameter name="socket"/>
+                        <raise scope="output" port="request_out" event="http_client_ready"/>
+                    </transition>
+                </state>
+
+                <state id="cooldown">
+                    <transition after="0.1" target="../connecting"/>
+                </state>
+
+                <transition after="self.timeout" target="../waiting">
+                    <raise scope="output" port="request_out" event="http_client_timeout"/>
+                </transition>
+            </state>
+
+            <parallel id="connected">
+                <state id="listening" initial="listen">
+                    <state id="listen">
+                        <onentry>
+                            <raise scope="output" port="socket_out" event="recv_socket">
+                                <parameter expr="self.socket"/>
+                            </raise>
+                        </onentry>
+                        <transition event="received_socket" port="socket_in" cond="(self.socket == socket) and (len(data) > 0)" target=".">
+                            <parameter name="socket"/>
+                            <parameter name="data"/>
+                            <script>
+                                self.received_data += data
+                            </script>
+                        </transition>
+                        <transition event="received_socket" port="socket_in" cond="(self.socket == socket) and (len(data) == 0)" target="../close">
+                            <parameter name="socket"/>
+                            <parameter name="data"/>
+                        </transition>
+                    </state>
+                    <state id="close">
+                    </state>
+                </state>
+
+                <state id="sending" initial="waiting_for_data">
+                    <state id="waiting_for_data">
+                        <transition cond="len(self.send_data) > 0" target="../transferring">
+                            <raise scope="output" port="socket_out" event="send_socket">
+                                <parameter expr="self.socket"/>
+                                <parameter expr="self.send_data"/>
+                            </raise>
+                        </transition>
+                    </state>
+                    <state id="transferring">
+                        <transition event="sent_socket" port="socket_in" cond="self.socket == socket" target="../waiting_for_data">
+                            <parameter name="socket"/>
+                            <parameter name="sent_bytes"/>
+                            <script>
+                                self.send_data = self.send_data[sent_bytes:]
+                            </script>
+                        </transition>
+                    </state>
+                </state>
+
+                <state id="queueing">
+                    <state id="queueing">
+                        <onentry>
+                        </onentry>
+                        <transition port="request_in" event="HTTP_input" target=".">
+                            <parameter name="data"/>
+                            <parameter name="ID"/>
+                            <script>
+                                self.send_data += "POST / HTTP/1.0\r\n"
+                                self.send_data += "Content-Length: %i\r\n" % len(str(data))
+                                self.send_data += "\r\n"
+                                self.send_data += data
+                                self.IDs.append(ID)
+                            </script>
+                        </transition>
+                    </state>
+                </state>
+
+                <state id="parsing" initial="wait_for_header">
+                    <state id="wait_for_header">
+                        <transition cond="'\r\n\r\n' in self.received_data" target="../wait_for_payload">
+                            <script>
+                                header, self.received_data = self.received_data.split("\r\n\r\n", 1)
+                                header = header.lower()
+                                if "content-length" in header:
+                                    _, after = header.split("content-length:", 1)
+                                    after, _ = after.split("\r\n", 1)
+                                    after = after.strip()
+                                    self.length = int(after)
+                                else:
+                                    self.length = float('inf')
+                            </script>
+                        </transition>
+                    </state>
+                    <state id="wait_for_payload">
+                        <transition cond="len(self.received_data) >= self.length and self.IDs[0] is not None" target="../wait_for_header">
+                            <script>
+                                data = self.received_data[:self.length]
+                                self.received_data = self.received_data[self.length:]
+                            </script>
+                            <raise event="HTTP_output" scope="output" port="request_out">
+                                <parameter expr="data"/>
+                                <parameter expr="self.IDs.pop(0)"/>
+                            </raise>
+                        </transition>
+
+                        <transition cond="len(self.received_data) >= self.length and self.IDs[0] is None" target="../wait_for_header">
+                            <script>
+                                # Drop data
+                                self.received_data = self.received_data[self.length:]
+                                self.IDs.pop(0)
+                            </script>
+                        </transition>
+                    </state>
+                </state>
+            </parallel>
+        </scxml>
+    </class>
+</diagram>

+ 249 - 228
wrappers/modelverse.py

@@ -1,13 +1,13 @@
 import urllib
-import urllib2
 import json
 import random
-from urllib2 import URLError
 import sys
 import time
 import threading
+import uuid
 
-COMPILER_PATH = "interface/HUTN"
+import sccd.runtime.socket2event as socket2event
+from sccd.runtime.statecharts_core import Event
 
 MODE_UNCONNECTED = 0
 MODE_UNAUTHORIZED = 1
@@ -17,10 +17,6 @@ MODE_DIALOG = 4
 MODE_MANUAL = 5
 MODE_SERVICE = 6
 
-# Bind to the compiler (might have to update path manually!)
-sys.path.append(COMPILER_PATH)
-from hutn_compiler.compiler import main as do_compile
-
 # Exceptions
 class ModelverseException(Exception):
     pass
@@ -60,12 +56,59 @@ class UnknownMetamodellingHierarchy(ModelverseException):
 
 # Helper functions and configuration: do not use yourself!
 taskname = None
-address = None
-last_output = None
 mode = MODE_UNCONNECTED
 prev_mode = None
 current_model = None
 registered_metamodels = {}
+outputs = {}
+ctrl_input = None
+ctrl_output = None
+
+def _output_thread(controller, outp, task):
+    req_out = controller.addOutputListener("request_out")
+    my_id = str(uuid.uuid4())
+
+    try:
+        while 1:
+            controller.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "get_output", "taskname": task}), my_id]))
+            event = req_out.fetch(-1)
+
+            if event.parameters[1] == my_id:
+                outp[task].append(json.loads(event.parameters[0]))
+    except:
+        raise
+
+def _exec_on_statechart(statechart):
+    def _exec_sc(controller, inport, outport):
+        global taskname
+        op = controller.addOutputListener(outport)
+
+        while 1:
+            if len(outputs[taskname]) > 1:
+                # Is an output message of the Mv, so put it in the SC
+                del outputs[taskname][0]
+                output_event = outputs[taskname][0]
+
+                if output_event == "Success" or output_event == "Failure":
+                    # Is a stop event!
+                    controller.addInput(Event("terminate", inport, []))
+                    break
+                else:
+                    # Is just a normal event!
+                    controller.addInput(Event("input", inport, [output_event]))
+
+            input_event = op.fetch(0)
+            if input_event is not None:
+                # Expand the event and make it HTTP input
+                _input(input_event.parameters)
+                
+            time.sleep(0.02)
+        
+    thrd = threading.Thread(target=_exec_sc, args=statechart)
+    thrd.daemon = True
+    thrd.start()
+
+    return None
 
 def _get_metamodel(model):
     global registered_metamodels
@@ -114,77 +157,47 @@ def _goto_mode(new_mode, model_name=None):
         # Go to a mode that we have no automatic transfer to: raise exception
         raise InvalidMode("Required mode: %s, current mode: %s" % (new_mode, mode))
 
-def _input(value, port=None):
+def _input(value, task=None):
     # Ugly json encoding of primitives
     #print("[IN] %s" % value)
-    if port is None:
-        port = taskname
+    if task is None:
+        task = taskname
     if isinstance(value, type([])):
         value = json.dumps(value)
-        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": value, "taskname": port}))).read()
+        ctrl_input.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "set_input", "taskname": task, "data": value}), None]))
     else:
         value = json.dumps(value)
-        #print("Set input: " + str(value))
-        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": port}))).read()
+        ctrl_input.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "set_input", "taskname": task, "value": value}), None]))
 
 def _input_raw(value, taskname):
     # Ugly json encoding of primitives
-    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
-
-    #TODO check that this is actually a Modelverse!
-
-def _compile_AL(code):
-    # Compile an action language file and send the compiled 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(".code.alc", "w") as f:
-        f.write(code)
-        f.flush()
-
-    compiled = do_compile(".code.alc", COMPILER_PATH + "/grammars/actionlanguage.g", "CS")
-    return compiled
-
-def _compile_model(code):
-    # Compile a model and send the compiled graph
-    # 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 do_compile(".model.mvc", COMPILER_PATH + "/grammars/modelling.g", "M")
-
-def _output(expected=None,port=None):
-    if port is None:
-        port = taskname
+    ctrl_input.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "set_input", "taskname": taskname, "value": value}), None]))
+
+def _output(expected=None, task=None):
+    if task is None:
+        task = taskname
+
     try:
-        global last_output
-        last_output = json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": port}))).read())
-        #print("[OUT] %s" % last_output)
+        while len(outputs[task]) < 2:
+            time.sleep(0.02)
+
+        del outputs[task][0]
+        #print("[OUT] %s" % outputs[0])
     except:
         raise UnknownError()
-    if expected is not None and last_output != expected:
-        raise InterfaceMismatch(_last_output(), expected)
-    return last_output
 
-def _last_output():
-    return last_output
+    if expected is not None and _last_output(task) != expected:
+        raise InterfaceMismatch(_last_output(task), expected)
+    return _last_output(task)
+
+def _last_output(task=None):
+    if task is None:
+        task = taskname
+
+    return outputs[task][0]
 
 # Raise common exceptions
-def _handle_output(requested=None, split=None):
+def _handle_output(requested=None, split=False):
     value = _output()
     if value.startswith("Model exists: "):
         raise ModelExists(value.split(": ", 1)[1])
@@ -199,14 +212,14 @@ def _handle_output(requested=None, split=None):
     elif value.startswith("Attribute not found: "):
         raise NoSuchAttribute(value.split(": ", 1)[1])
     elif requested is not None and value.startswith(requested):
-        if split is None:
+        if not split:
             return value
         else:
-            splitted = value.strip().split(split, 1)
-            if len(splitted) == 1:
-                return ""
+            splitted = value.strip().split(" ", 1)
+            if len(splitted) > 1:
+                return splitted[1].split("\n")
             else:
-                return splitted[1].rstrip()
+                return []
     else:
         raise InterfaceMismatch(value)
     
@@ -251,25 +264,75 @@ def alter_context(model_name, metamodel_name):
     global registered_metamodels
     registered_metamodels[model_name] = metamodel_name
 
+def _start_http_client(addr, port, timeout):
+    import http_client
+    ctrl = http_client.Controller()
+    listener = ctrl.addOutputListener("request_out")
+    socket2event.boot_translation_service(ctrl)
+    thrd = threading.Thread(target=ctrl.start)
+    thrd.daemon = True
+    thrd.start()
+
+    evt = listener.fetch(-1)
+    if evt.name != "http_client_initialized":
+        raise Exception("HTTP client did not behave as expected during init: " + str(evt.name))
+
+    ctrl.addInput(Event("connect", "request_in", [(addr, port), timeout]))
+
+    evt = listener.fetch(-1)
+
+    if evt.name == "http_client_timeout":
+        raise Exception("HTTP client timeout")
+    if evt.name != "http_client_ready":
+        raise Exception("HTTP client did not behave as expected during connect: " + str(evt.name))
+
+    return ctrl
+
 # Main MvC operations
-def init(address_param="http://127.0.0.1:8001", timeout=20.0):
+def init(address_param="127.0.0.1:8001", timeout=20.0):
     """Starts up the connection to the Modelverse."""
-    global mode
+    # Start up the HTTP Client SC
+    global ctrl_input
+    global ctrl_output
+
+    if ctrl_input is not None:
+        ctrl_input.stop()
+    if ctrl_output is not None:
+        ctrl_output.stop()
+
     global address
-    global taskname
-    address = address_param
+    global port
+
+    address, port = address_param.split(":", 1)
+    port = int(port)
+    
+    ctrl_input = _start_http_client(address, port, timeout)
+    ctrl_output = _start_http_client(address, port, timeout) 
+    controllers = [ctrl_input, ctrl_output]
+
+    global mode
     start_time = time.time()
-    taskname = random.random()
-    while 1:
-        try:
-            _input_raw('"%s"' % taskname, "task_manager")
-            mode = MODE_UNAUTHORIZED
-            break
-        except URLError as e:
-            if time.time() - start_time > timeout:
-                raise ConnectionError(e.reason)
-            else:
-                time.sleep(0.1)
+    task = str(random.random())
+
+    _input_raw('"%s"' % task, "task_manager")
+
+    mode = MODE_UNAUTHORIZED
+
+    global outputs
+    global taskname
+    taskname = task
+    outputs = {}
+
+    _listen_to_output(ctrl_output, task)
+
+def _listen_to_output(controller, task):
+    global outputs
+    outputs[task] = [None]
+
+    # This re-assign also diconnects the previous get_output connections to the outputs variable
+    thrd = threading.Thread(target=_output_thread, args=[controller, outputs, task])
+    thrd.daemon = True
+    thrd.start()
 
 def login(username, password):
     """Log in a user, if user doesn't exist, it is created."""
@@ -305,34 +368,20 @@ def login(username, password):
     else:
         raise InterfaceMismatch(_last_output())
 
-def model_add(model_name, metamodel_name, model_code=None):
+def model_add(model_name, metamodel_name, model_code=""):
     """Instantiate a new model."""
     _goto_mode(MODE_MODELLING)
 
-    # Do this before creating the model, as otherwise compilation errors would make us inconsistent
-    if model_code is not None:
-        try:
-            compiled = _compile_model(model_code)
-        except Exception as e:
-            raise CompilationError(e)
-    else:
-        compiled = [0]
-
     _input(["model_add", metamodel_name, model_name])
     _handle_output("Waiting for model constructors...")
-    _input(compiled)
+    _input(model_code)
     _output("Success")
 
     global registered_metamodels
     registered_metamodels[model_name] = metamodel_name
 
 def upload_code(code):
-    try:
-        compiled = _compile_AL(code)
-    except Exception as e:
-        raise CompilationError(e)
-
-    _input(compiled)
+    _input(code)
 
 def model_delete(model_name):
     """Delete an existing model."""
@@ -345,19 +394,16 @@ def model_list(location):
     """List all models."""
     _goto_mode(MODE_MODELLING)
     _input(["model_list", location])
-    return set(_handle_output("Success: ", split=" ").split("\n"))
+    return set(_handle_output("Success: ", split=True))
 
 def model_list_full(location):
     """List full information on all models."""
     _goto_mode(MODE_MODELLING)
     _input(["model_list_full", location])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
+    output = _handle_output("Success: ", split=True)
 
     lst = set([])
-    value = output.strip().split("\n")
-    for v in value:
+    for v in output:
         m = v.strip()
         perm, own, grp, m = m.split(" ", 3)
         lst.add((m, own, grp, perm))
@@ -372,23 +418,15 @@ def verify(model_name, metamodel_name=None):
         metamodel_name = _get_metamodel(model_name)
 
     _input(["verify", model_name, metamodel_name])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
-def model_overwrite(model_name, new_model=None, metamodel_name=None):
+def model_overwrite(model_name, new_model="", metamodel_name=None):
     """Upload a new model and overwrite an existing model."""
     _goto_mode(MODE_MODIFY, model_name)
 
-    if new_model is not None:
-        try:
-            compiled = _compile_model(new_model)
-        except Exception as e:
-            raise CompilationError(e)
-    else:
-        compiled = [0]
-
     _input("upload")
     _handle_output("Waiting for model constructors...")
-    _input(compiled)
+    _input(new_model)
     _output("Success")
 
     if metamodel_name is not None:
@@ -414,30 +452,19 @@ def model_render(model_name, mapper_name):
     _goto_mode(MODE_MODELLING)
 
     _input(["model_render", model_name, mapper_name])
-    return json.loads(_handle_output("Success: ", split=" "))
+    return json.loads(_handle_output("Success: ", split=True)[0])
 
 def transformation_between(source, target):
     _goto_mode(MODE_MODELLING)
 
     _input(["transformation_between", source, target])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    return set([v for v in output.split("\n")])
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def transformation_add_MT(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
     """Create a new model transformation."""
     global mode
     _goto_mode(MODE_MODELLING)
-    import time
-
-    start = time.time()
-    try:
-        compiled = _compile_model(code)
-    except Exception as e:
-        raise CompilationError(e)
-    #print("Compilation took: %ss" % (time.time() - start))
-    start = time.time()
 
     mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
     _input(["transformation_add_MT"] + mv_dict_rep + [operation_name])
@@ -449,25 +476,17 @@ def transformation_add_MT(source_metamodels, target_metamodels, operation_name,
         callback()
         _input("exit")
         mode = MODE_MODELLING
-    #print("Callbacks took: %ss" % (time.time() - start))
-    start = time.time()
 
     # Done, so RAMify and upload the model
     _handle_output("Waiting for model constructors...")
-    _input(compiled)
+    _input(code)
     _handle_output("Success")
-    #print("Upload and RAMify took: %ss" % (time.time() - start))
 
 def transformation_add_AL(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
     """Create a new action language model, which can be executed."""
     global mode
     _goto_mode(MODE_MODELLING)
 
-    try:
-        compiled = _compile_AL(code)
-    except Exception as e:
-        raise CompilationError(e)
-
     mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
     _input(["transformation_add_AL"] + mv_dict_rep + [operation_name])
 
@@ -480,7 +499,7 @@ def transformation_add_AL(source_metamodels, target_metamodels, operation_name,
         mode = MODE_MODELLING
 
     _handle_output("Waiting for code constructors...")
-    _input(compiled)
+    _input(code)
     _output("Success")
 
 def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_name, callback=lambda: None):
@@ -501,7 +520,7 @@ def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_na
 
     _handle_output("Success")
 
-def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
+def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, statechart=None):
     """Execute an existing model operation."""
     global mode
     _goto_mode(MODE_MODELLING)
@@ -511,19 +530,21 @@ def transformation_execute_AL(operation_name, input_models_dict, output_models_d
     _input(["transformation_execute", operation_name] + mv_dict_rep)
     _handle_output("Success: ready for AL execution")
 
-    # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
-    while _output() not in ["Success", "Failure"]:
+    if statechart is not None:
+        # We are to delegate this information to another statechart, which wants interaction
+        # As such, we continue on a different thread, where we pipe the information, and let this call return immediately
         mode = MODE_DIALOG
-        reply = callback(_last_output())
+        _exec_on_statechart(statechart)
         mode = MODE_MODELLING
-        if reply is not None:
-            _input(reply)
-
-    # Got termination message, so we are done!
-    if _last_output() == "Success":
-        return True
+        return None
     else:
-        return False
+        # No statechart associated, so just wait until we are finished
+        while _output() not in ["Success", "Failure"]:
+            pass
+        if _last_output() == "Success":
+            return True
+        else:
+            return False
 
 def transformation_execute_MANUAL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
     """Execute an existing model operation."""
@@ -552,7 +573,7 @@ def transformation_execute_MANUAL(operation_name, input_models_dict, output_mode
     else:
         return False
 
-def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
+def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, statechart=None):
     """Execute an existing model operation."""
     global mode
     _goto_mode(MODE_MODELLING)
@@ -562,32 +583,31 @@ def transformation_execute_MT(operation_name, input_models_dict, output_models_d
     _input(["transformation_execute", operation_name] + mv_dict_rep)
     _handle_output("Success: ready for MT execution")
 
-    # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
-    while _output() not in ["Success", "Failure"]:
+    if statechart is not None:
+        # We are to delegate this information to another statechart, which wants interaction
+        # As such, we continue on a different thread, where we pipe the information, and let this call return immediately
         mode = MODE_DIALOG
-        reply = callback(_last_output())
+        _exec_on_statechart(statechart)
         mode = MODE_MODELLING
-        if reply is not None:
-            _input(reply)
-
-    # Got termination message, so we are done!
-    if _last_output() == "Success":
-        return True
+        return None
     else:
-        return False
+        # No statechart associated, so just wait until we are finished
+        while _output() not in ["Success", "Failure"]:
+            pass
+        if _last_output() == "Success":
+            return True
+        else:
+            return False
 
 def transformation_list():
     """List existing model operations."""
     _goto_mode(MODE_MODELLING)
 
     _input("transformation_list")
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
+    output = _handle_output("Success: ", split=True)
 
     lst = set([])
-    value = output.strip().split("\n")
-    for v in value:
+    for v in output:
         t, m = v.strip().split(" ", 1)
         t = t[1:-1].strip()
         m = m.strip().split(":")[0].strip()
@@ -709,10 +729,8 @@ def element_list(model_name):
 
     _input("list_full")
     lst = set([])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    for v in output.split("\n"):
+    output = _handle_output("Success: ", split=True)
+    for v in output:
         m, mm = v.split(":")
         m = m.strip()
         mm = mm.strip()
@@ -725,10 +743,8 @@ def types(model_name):
 
     _input("types")
     lst = set([])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    for v in output.split("\n"):
+    output = _handle_output("Success: ", split=True)
+    for v in output:
         m, mm = v.split(":")
         m = m.strip()
         lst.add(m)
@@ -740,10 +756,8 @@ def types_full(model_name):
 
     _input("types")
     lst = set([])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    for v in output.split("\n"):
+    output = _handle_output("Success: ", split=True)
+    for v in output:
         m, mm = v.split(":")
         m = m.strip()
         mm = mm.strip()
@@ -755,8 +769,7 @@ def read(model_name, ID):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read", ID])
-    output = _handle_output("Success: ", split=" ")
-    v = output.split("\n")
+    v = _handle_output("Success: ", split=True)
     t = v[1].split(":")[1].strip()
     if (not v[2].startswith("Source:")):
         rval = (t, None)
@@ -771,11 +784,10 @@ def read_attrs(model_name, ID):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read", ID])
-    output = _handle_output("Success: ", split=" ")
-    v = output.split("\n")
+    output = _handle_output("Success: ", split=True)
     searching = True
     rval = {}
-    for r in v:
+    for r in output:
         if searching:
             if r == "Attributes:":
                 # Start working on attributes
@@ -804,7 +816,7 @@ def instantiate(model_name, typename, edge=None, ID=""):
         _input(["instantiate_node", typename, ID])
     else:
         _input(["instantiate_edge", typename, ID, edge[0], edge[1]])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 def delete_element(model_name, ID):
     """Delete the element with the given ID"""
@@ -824,16 +836,12 @@ def attr_assign(model_name, ID, attr, value):
 def attr_assign_code(model_name, ID, attr, code):
     """Assign a piece of Action Language code to the attribute"""
     _check_type(code)
-    try:
-        compiled = _compile_AL(code)
-    except Exception as e:
-        raise CompilationError(e)
 
     _goto_mode(MODE_MODIFY, model_name)
 
-    _input(["attr_add", ID, attr])
+    _input(["attr_add_code", ID, attr])
     _handle_output("Waiting for code constructors...")
-    _input(compiled)
+    _input(code)
     _output("Success")
 
 def attr_delete(model_name, ID, attr):
@@ -848,45 +856,47 @@ def read_outgoing(model_name, ID, typename):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_outgoing", ID, typename])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def read_incoming(model_name, ID, typename):
     """Returns a list of all incoming associations of a specific type ("" = all)"""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_incoming", ID, typename])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def read_association_source(model_name, ID):
     """Returns the source of an association."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_association_source", ID])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 def read_association_destination(model_name, ID):
     """Returns the destination of an association."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_association_destination", ID])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 ##### To document:
 
 def service_register(name, function):
     """Register a function as a service with a specific name."""
 
-    def service_process(port):
+    def service_process(service_task):
+        global address
+        global port
+
+        ctrl = _start_http_client(address, port, 10.0) 
+        _listen_to_output(ctrl, service_task)
         while 1:
-            thrd = threading.Thread(target=function, args=[service_get(port)])
+            client_task = service_get(service_task)
+            ctrl = _start_http_client(address, port, 10.0) 
+            _listen_to_output(ctrl, client_task)
+            thrd = threading.Thread(target=function, args=[client_task])
             thrd.daemon = True
             thrd.start()
 
@@ -897,10 +907,12 @@ def service_register(name, function):
 
     # Now we are in service-mode
     mode = MODE_SERVICE
-    port = _handle_output("Success: ", split=" ")
+    task = _handle_output("Success: ", split=True)[0]
 
     # Process events in the background!
-    threading.Thread(target=service_process, args=[port]).start()
+    thrd = threading.Thread(target=service_process, args=[task])
+    thrd.daemon = True
+    thrd.start()
 
 def service_stop():
     """Stop the currently executing process."""
@@ -911,18 +923,19 @@ def service_stop():
     global mode
     mode = MODE_MODELLING
 
-def service_get(port):
-    """Get the values on the specified port."""
+def service_get(task):
+    """Get the values on the specified task."""
     _goto_mode(MODE_SERVICE)
 
-    return _output(port=port)
+    val = _output(task=task)
+    return val
 
-def service_set(port, value):
-    """Set a value on a specified port."""
+def service_set(task, value):
+    """Set a value on a specified task."""
     _check_type_list(value)
     _goto_mode(MODE_SERVICE)
 
-    _input(value, port=port)
+    _input(value, task=task)
 
 def user_password(user, password):
     """Change a user's password."""
@@ -938,7 +951,7 @@ def element_list_nice(model_name):
 
     _input(["element_list_nice", model_name, _get_metamodel(model_name)])
 
-    data = _handle_output("Success: ", split=" ")
+    data = _handle_output("Success: ", split=True)[0]
     try:
         return json.loads(data)
     except:
@@ -950,29 +963,23 @@ def connections_between(model_name, source_element, target_element):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["connections_between", source_element, target_element])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def define_attribute(model_name, node, attr_name, attr_type):
     """Create a new attribute, which can be instantiated one meta-level below."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["define_attribute", node, attr_name, attr_type])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 def all_instances(model_name, type_name):
     """Returns a list of all elements of a specific type."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["all_instances", type_name])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def service_poll(port):
     """Checks whether or not the Modelverse side has any input ready to be processed."""
@@ -996,6 +1003,20 @@ def add_conformance(model_name, metamodel_name, partial_type_mapping=None):
     _handle_output("Success")
 
 def folder_create(folder_name):
+    """Create a new folder."""
     _goto_mode(MODE_MODELLING)
     _input(["folder_create", folder_name])
     _handle_output("Success")
+
+def model_types(model_name):
+    """Fetch all typings defined for this specific model."""
+    _goto_mode(MODE_MODELLING)
+    _input(["model_types", model_name])
+    output = _handle_output("Success: ", split=True)
+    return set(output)
+
+import atexit
+def _close_model():
+    if mode == MODE_MODIFY:
+        _model_exit()
+atexit.register(_close_model)

+ 115 - 0
wrappers/poll_print.py

@@ -0,0 +1,115 @@
+"""
+Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)
+
+Date:   Mon Aug 28 10:54:41 2017
+
+Model author: Yentl Van Tendeloo
+Model name:   Logging
+Model description:
+For testing: I/O Statechart for the Modelverse
+"""
+
+from sccd.runtime.statecharts_core import *
+
+# package "Logging"
+
+class Logging(RuntimeClassBase):
+    def __init__(self, controller):
+        RuntimeClassBase.__init__(self, controller)
+        
+        self.semantics.big_step_maximality = StatechartSemantics.TakeMany
+        self.semantics.internal_event_lifeline = StatechartSemantics.Queue
+        self.semantics.input_event_lifeline = StatechartSemantics.FirstComboStep
+        self.semantics.priority = StatechartSemantics.SourceParent
+        self.semantics.concurrency = StatechartSemantics.Single
+        
+        # build Statechart structure
+        self.build_statechart_structure()
+        
+        # call user defined constructor
+        Logging.user_defined_constructor(self)
+    
+    def user_defined_constructor(self):
+        pass
+    
+    def user_defined_destructor(self):
+        pass
+    
+    
+    # builds Statechart structure
+    def build_statechart_structure(self):
+        
+        # state <root>
+        self.states[""] = State(0, "", self)
+        
+        # state /init
+        self.states["/init"] = State(1, "/init", self)
+        self.states["/init"].setEnter(self._init_enter)
+        self.states["/init"].setExit(self._init_exit)
+        
+        # state /finished
+        self.states["/finished"] = State(2, "/finished", self)
+        
+        # add children
+        self.states[""].addChild(self.states["/init"])
+        self.states[""].addChild(self.states["/finished"])
+        self.states[""].fixTree()
+        self.states[""].default_state = self.states["/init"]
+        
+        # transition /init
+        _init_0 = Transition(self, self.states["/init"], [self.states["/init"]])
+        _init_0.setAction(self._init_0_exec)
+        _init_0.setTrigger(Event("input", "inp"))
+        self.states["/init"].addTransition(_init_0)
+        _init_1 = Transition(self, self.states["/init"], [self.states["/init"]])
+        _init_1.setTrigger(Event("_0after"))
+        self.states["/init"].addTransition(_init_1)
+        _init_2 = Transition(self, self.states["/init"], [self.states["/finished"]])
+        _init_2.setTrigger(Event("terminate", "inp"))
+        self.states["/init"].addTransition(_init_2)
+        _init_3 = Transition(self, self.states["/init"], [self.states["/init"]])
+        _init_3.setAction(self._init_3_exec)
+        _init_3.setTrigger(Event("raw_inp", "user_inp"))
+        self.states["/init"].addTransition(_init_3)
+    
+    def _init_enter(self):
+        self.addTimer(0, 0.1)
+    
+    def _init_exit(self):
+        self.removeTimer(0)
+    
+    def _init_0_exec(self, parameters):
+        value = parameters[0]
+        print(value)
+    
+    def _init_3_exec(self, parameters):
+        inp = parameters[0]
+        print("Got raw input")
+        self.big_step.outputEvent(Event("output", "outp", [inp]))
+    
+    def initializeStatechart(self):
+        # enter default state
+        self.default_targets = self.states["/init"].getEffectiveTargetStates()
+        RuntimeClassBase.initializeStatechart(self)
+
+class ObjectManager(ObjectManagerBase):
+    def __init__(self, controller):
+        ObjectManagerBase.__init__(self, controller)
+    
+    def instantiate(self, class_name, construct_params):
+        if class_name == "Logging":
+            instance = Logging(self.controller)
+            instance.associations = {}
+        else:
+            raise Exception("Cannot instantiate class " + class_name)
+        return instance
+
+class Controller(ThreadsControllerBase):
+    def __init__(self, keep_running = None, behind_schedule_callback = None):
+        if keep_running == None: keep_running = True
+        if behind_schedule_callback == None: behind_schedule_callback = None
+        ThreadsControllerBase.__init__(self, ObjectManager(self), keep_running, behind_schedule_callback)
+        self.addInputPort("user_inp")
+        self.addInputPort("inp")
+        self.addOutputPort("outp")
+        self.object_manager.createInstance("Logging", [])

+ 43 - 0
wrappers/poll_print.xml

@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<diagram author="Yentl Van Tendeloo" name="Logging">
+    <description>
+        For testing: I/O Statechart for the Modelverse
+    </description>
+
+    <inport name="user_inp"/>
+    <inport name="inp"/>
+    <outport name="outp"/>
+
+    <class name="Logging" default="true">
+        <scxml initial="init">
+            <state id="init">
+                <transition event="input" port="inp" target=".">
+                    <parameter name="value"/>
+                    <script>
+                        print(value)
+                    </script>
+                </transition>
+
+                <transition after="0.1" target="."/>
+
+                <transition event="terminate" port="inp" target="../finished"/>
+
+                <transition event="raw_inp" port="user_inp" target=".">
+                    <parameter name="inp"/>
+                    <script>
+                        print("Got raw input")
+                    </script>
+                    <raise event="output" port="outp" scope="output">
+                        <parameter expr="inp"/>
+                    </raise>
+                </transition>
+            </state>
+
+            <state id="finished">
+                <script>
+                    print("FINISHED")
+                </script>
+            </state>
+        </scxml>
+    </class>
+</diagram>

+ 7 - 7
wrappers/test.py

@@ -50,18 +50,18 @@ login("admin", "admin")
 # Add the metamodels for PetriNet and ReachabilityGraph
 print("Add metamodels")
 try:
-    model_add("PetriNet", "SimpleClassDiagrams", open("models/petrinets.mvc").read())
+    model_add("formalisms/PetriNet", "formalisms/SimpleClassDiagrams", open("models/petrinets.mvc").read())
 except ModelExists:
     pass
 
 try:
-    model_add("ReachabilityGraph", "SimpleClassDiagrams", open("models/reachability_graph.mvc").read())
+    model_add("formalisms/ReachabilityGraph", "formalisms/SimpleClassDiagrams", open("models/reachability_graph.mvc").read())
 except ModelExists:
     pass
 
 print("Add model")
 try:
-    model_add("my_pn", "PetriNet", open("models/my_pn.mvc").read())
+    model_add("models/my_pn", "formalisms/PetriNet", open("models/my_pn.mvc").read())
 except ModelExists:
     pass
 
@@ -75,22 +75,22 @@ except ModelverseException:
 # Add the action language code to transform between them
 print("Add AL model")
 try:
-    transformation_add_AL({"PetriNet": "PetriNet"}, {"ReachabilityGraph": "ReachabilityGraph"}, "analyseReachability", open("models/reachability.alc", "r").read())
+    transformation_add_AL({"PetriNet": "formalisms/PetriNet"}, {"ReachabilityGraph": "formalisms/ReachabilityGraph"}, "models/analyseReachability", open("models/reachability.alc", "r").read())
 except ModelExists:
     pass
 
 # Add an example model transformation to print the reachability graph
 print("Add MT model")
 try:
-    transformation_add_MT({"ReachabilityGraph": "ReachabilityGraph"}, {}, "printReachability", open("models/reachabilitygraph_print.mvc").read())
+    transformation_add_MT({"ReachabilityGraph": "formalisms/ReachabilityGraph"}, {}, "models/printReachability", open("models/reachabilitygraph_print.mvc").read())
 except ModelExists:
     pass
 
 # Do the reachability graph generation
 print("Execute AL")
-status = transformation_execute_AL("analyseReachability", {"PetriNet": "my_pn"}, {"ReachabilityGraph": "my_reachability"}, callback=print_mv_with_input)
+status = transformation_execute_AL("models/analyseReachability", {"PetriNet": "models/my_pn"}, {"ReachabilityGraph": "models/my_reachability"}, callback=print_mv_with_input)
 print("Reachability generation success: " + str(status))
 
 print("Execute MT")
-status = transformation_execute_MT("printReachability", {"ReachabilityGraph": "my_reachability"}, {}, callback=print_mv)
+status = transformation_execute_MT("models/printReachability", {"ReachabilityGraph": "models/my_reachability"}, {}, callback=print_mv)
 print("Reachability printing success: " + str(status))

+ 16 - 11
wrappers/test_SCCD.py

@@ -1,6 +1,7 @@
 import sys
 sys.path.append("wrappers")
 from modelverse import *
+from sccd.runtime.statecharts_core import Event
 
 init()
 login("admin", "admin")
@@ -19,19 +20,23 @@ except ModelExists:
 # Update the model of the traffic light
 if "my_SCCD" in [i[0] for i in model_list("models")]:
     model_delete("models/my_SCCD")
-#model_add("models/my_SCCD", "formalisms/SCCD", open("models/dynamic_trafficlight.mvc", 'r').read())
-model_add("models/my_SCCD", "formalisms/SCCD", open("integration/code/SCCD_all.mvc", 'r').read())
+model_add("models/my_SCCD", "formalisms/SCCD", open("models/dynamic_trafficlight.mvc", 'r').read())
 
 # Add SCCD execution semantics
 transformation_add_AL({"SCCD": "formalisms/SCCD"}, {"trace": "formalisms/SCCD_Trace"}, "models/SCCD_execute", open("models/SCCD_execute.alc", 'r').read())
 
-# Execute it, while interacting through the console
-def callback(inp):
-    print(inp)
-    inp = raw_input()
-    if inp == "":
-        return None
-    else:
-        return inp
+import poll_print
+ctrl = poll_print.Controller(keep_running=False)
 
-transformation_execute_AL("models/SCCD_execute", {"SCCD": "models/my_SCCD"}, {"trace": "models/my_trace"}, callback=callback)
+thrd = threading.Thread(target=ctrl.start)
+thrd.daemon = True
+thrd.start()
+
+transformation_execute_AL("models/SCCD_execute", {"SCCD": "models/my_SCCD"}, {"trace": "models/my_trace"}, statechart=(ctrl, "inp", "outp"))
+
+import select
+while thrd.is_alive():
+    if select.select([sys.stdin], [], [], 0.1)[0]:
+        ctrl.addInput(Event("raw_inp", "user_inp", [sys.stdin.readline().strip()]))
+
+thrd.join()

+ 0 - 3
wrappers/test_service.py

@@ -13,12 +13,9 @@ def fibonacci_service(port):
     service_set(port, fibonacci(service_get(port)))
     
 service_register("fibonacci", fibonacci_service)
-print("Registered")
 
 while raw_input() != "STOP":
     # Stay active, as we shouldn't exit while the service is running!
     pass
-print("Stopping")
 
 service_stop()
-print("Service halted")

+ 0 - 3
wrappers/test_service_client.py

@@ -2,8 +2,5 @@ from modelverse import *
 
 init()
 login("admin", "admin")
-print("Upload AL")
 transformation_add_AL({}, {}, "test_services", open("integration/code/simple_client.alc", 'r').read())
-print("DONE")
 transformation_execute_AL("test_services", {}, {})
-print("Executed")