Simon Van Mierlo пре 9 година
родитељ
комит
a6d8925aa9
100 измењених фајлова са 1539 додато и 3583 уклоњено
  1. 4 19
      bootstrap/bootstrap.py
  2. 71 61
      bootstrap/constructors.alc
  3. 0 75
      bootstrap/modelling.alc
  4. 2 82
      doc/actionlanguage.rst
  5. 0 14
      doc/advanced.rst
  6. 0 99
      doc/examples.rst
  7. 5 114
      doc/howto.rst
  8. 5 10
      doc/index.rst
  9. 6 4
      doc/installation.rst
  10. 10 17
      doc/internal.rst
  11. 39 12
      doc/modellanguage.rst
  12. 0 2
      doc/upload.sh
  13. 175 118
      hybrid_server/classes/mvkcontroller.xml
  14. 146 0
      hybrid_server/classes/task.xml
  15. 1 0
      hybrid_server/server.xml
  16. 47 52
      integration/code/cbd_design.mvc
  17. 0 77
      integration/code/cbd_runtime.mvc
  18. 0 654
      integration/code/cbd_semantics.alc
  19. 0 32
      integration/code/fsa_design.mvc
  20. 0 42
      integration/code/fsa_runtime.mvc
  21. 0 256
      integration/code/fsa_semantics.alc
  22. 0 12
      integration/code/ftg.mvc
  23. 0 8
      integration/code/graph.mvc
  24. 3 5
      integration/code/initialize_PN.mvc
  25. 13 15
      integration/code/my_cbd.mvc
  26. 0 19
      integration/code/my_petrinet.mvc
  27. 0 33
      integration/code/my_petrinet_with_MM.mvc
  28. 0 48
      integration/code/my_petrinet_with_MM_and_constraints.mvc
  29. 10 16
      integration/code/petrinets.mvc
  30. 0 36
      integration/code/petrinets_constraints.mvc
  31. 36 38
      integration/code/pm_pn_reachability.mvc
  32. 0 16
      integration/code/pn_critical_section.mvc
  33. 14 20
      integration/code/pn_design.mvc
  34. 23 29
      integration/code/pn_design_model.mvc
  35. 0 63
      integration/code/pn_design_model_larger.mvc
  36. 165 170
      integration/code/pn_design_to_runtime.mvc
  37. 18 23
      integration/code/pn_print.mvc
  38. 16 22
      integration/code/pn_runtime.mvc
  39. 24 30
      integration/code/pn_runtime_model.mvc
  40. 161 166
      integration/code/pn_runtime_to_design.mvc
  41. 0 153
      integration/code/pn_semantics.alc
  42. 120 125
      integration/code/pn_simulate.mvc
  43. 0 91
      integration/code/ramified_petrinets.mvc
  44. 51 53
      integration/code/reachability_graph.mvc
  45. 184 0
      integration/code/reachability_subfunction.alc
  46. 58 60
      integration/code/reachabilitygraph_print.mvc
  47. 0 166
      integration/code/several_petrinets.mvc
  48. 0 31
      integration/code/simpleclassdiagrams.mvc
  49. 33 1
      integration/test_mvc.py
  50. 1 5
      interface/HUTN/grammars/modelling.g
  51. 56 0
      interface/HUTN/grammars/modelling_bootstrap.g
  52. 2 8
      interface/HUTN/hutn_compiler/bootstrap_visitor.py
  53. 1 12
      interface/HUTN/hutn_compiler/compiler.py
  54. 0 89
      interface/HUTN/hutn_compiler/constructors_object_visitor.py
  55. 0 35
      interface/HUTN/hutn_compiler/linker.py
  56. 0 32
      interface/HUTN/hutn_compiler/model_object_visitor.py
  57. 9 28
      interface/HUTN/hutn_compiler/model_visitor.py
  58. 0 83
      interface/HUTN/hutn_compiler/primitives_object_visitor.py
  59. 0 2
      interface/HUTN/includes/constructors.alh
  60. 2 2
      interface/HUTN/test/constructor_compilation_action_language/code/include.al
  61. 0 0
      interface/HUTN/test/grammar_action_language/code/accumulate.alc
  62. 0 0
      interface/HUTN/test/grammar_action_language/code/action.alc
  63. 0 0
      interface/HUTN/test/grammar_action_language/code/assign.alc
  64. 0 0
      interface/HUTN/test/grammar_action_language/code/assign_to_constant.alc
  65. 0 0
      interface/HUTN/test/grammar_action_language/code/assign_to_func_result.alc
  66. 0 0
      interface/HUTN/test/grammar_action_language/code/assign_to_statement.alc
  67. 0 0
      interface/HUTN/test/grammar_action_language/code/dictionary_selection.alc
  68. 0 0
      interface/HUTN/test/grammar_action_language/code/empty.alc
  69. 0 0
      interface/HUTN/test/grammar_action_language/code/fibonacci.alc
  70. 0 0
      interface/HUTN/test/grammar_action_language/code/full_empty.alc
  71. 0 0
      interface/HUTN/test/grammar_action_language/code/funcdef_empty_body.alc
  72. 0 0
      interface/HUTN/test/grammar_action_language/code/global.alc
  73. 0 0
      interface/HUTN/test/grammar_action_language/code/if.alc
  74. 0 0
      interface/HUTN/test/grammar_action_language/code/if_empty_body.alc
  75. 0 0
      interface/HUTN/test/grammar_action_language/code/if_empty_else.alc
  76. 0 0
      interface/HUTN/test/grammar_action_language/code/if_no_condition.alc
  77. 0 0
      interface/HUTN/test/grammar_action_language/code/if_only_else.alc
  78. 0 4
      interface/HUTN/test/grammar_action_language/code/include.al
  79. 4 0
      interface/HUTN/test/grammar_action_language/code/include.alc
  80. 0 0
      interface/HUTN/test/grammar_action_language/code/include_late.alc
  81. 9 0
      interface/HUTN/test/grammar_action_language/code/nested.alc
  82. 0 0
      interface/HUTN/test/grammar_action_language/code/primitives.alc
  83. 0 0
      interface/HUTN/test/grammar_action_language/code/return_in_assign.alc
  84. 0 0
      interface/HUTN/test/grammar_action_language/code/types.alc
  85. 0 0
      interface/HUTN/test/grammar_action_language/code/vardecl.alc
  86. 0 0
      interface/HUTN/test/grammar_action_language/code/while.alc
  87. 0 0
      interface/HUTN/test/grammar_action_language/code/while_empty_body.alc
  88. 0 0
      interface/HUTN/test/grammar_action_language/code/while_no_condition.alc
  89. 2 0
      interface/HUTN/test/grammar_action_language/test_invalids.py
  90. 13 16
      interface/HUTN/test/grammar_action_language/test_valids.py
  91. 0 0
      interface/HUTN/test/graph_compilation_action_language/__init__.py
  92. 0 7
      interface/HUTN/test/graph_compilation_action_language/code/action.al
  93. 0 3
      interface/HUTN/test/graph_compilation_action_language/code/assign.al
  94. 0 2
      interface/HUTN/test/graph_compilation_action_language/code/assign_invalid.al
  95. 0 9
      interface/HUTN/test/graph_compilation_action_language/code/dict_access.al
  96. 0 2
      interface/HUTN/test/graph_compilation_action_language/code/dictionary.al
  97. 0 15
      interface/HUTN/test/graph_compilation_action_language/code/factorial.al
  98. 0 15
      interface/HUTN/test/graph_compilation_action_language/code/fibonacci.al
  99. 0 25
      interface/HUTN/test/graph_compilation_action_language/code/fibonacci_smart.al
  100. 0 0
      interface/HUTN/test/graph_compilation_action_language/code/float.al

+ 4 - 19
bootstrap/bootstrap.py

@@ -18,7 +18,6 @@ def bootstrap():
                     ]
 
     task_frame = [  "evalstack",
-                    "symbols",
                     "returnvalue",
                     ]
 
@@ -187,11 +186,11 @@ def bootstrap():
                 # Bind task to the root
                 f.write('Dict (root, "%s", task_root)\n' % (task_manager))
 
-                def compile_code_AL(filename, target, prepend="", main=False, symbols=None):
+                def compile_code_AL(filename, target, prepend="", main=False):
                     import sys
                     sys.path.append("interface/HUTN/")
                     from hutn_compiler.compiler import main as compile_code
-                    code = compile_code(filename, "interface/HUTN/grammars/actionlanguage.g", "BS", ["--debug", "--prepend:%s" % prepend, "--main" if main else "--not-main"], symbols=symbols)
+                    code = compile_code(filename, "interface/HUTN/grammars/actionlanguage.g", "BS", ["--debug", "--prepend:%s" % prepend, "--main" if main else "--not-main"])
                     return code.replace("auto_initial_IP", target)
 
                 # Create all library code
@@ -203,7 +202,7 @@ def bootstrap():
                     import sys
                     sys.path.append("interface/HUTN/")
                     from hutn_compiler.compiler import main as compile_code
-                    model_code = compile_code(filename, "interface/HUTN/grammars/modelling.g", "MB", ["--modelname:%s" % model_name])
+                    model_code = compile_code(filename, "interface/HUTN/grammars/modelling_bootstrap.g", "MB", ["--modelname:%s" % model_name])
                     return model_code + "\n"
 
                 # Compile all model definitions to ALC directly
@@ -234,8 +233,7 @@ def bootstrap():
                     # Compile the subfile
                     bootstrap_file = bootstrap_file.replace("\\", "/")
                     print("[ALC] %s" % bootstrap_file)
-                    symbols = {}
-                    f.write(compile_code_AL(bootstrap_file, "initial_IP", prepend=bootstrap_file, symbols=symbols, main = bootstrap_file in [initial_code_manager, initial_code_task]), both=False)
+                    f.write(compile_code_AL(bootstrap_file, "initial_IP", prepend=bootstrap_file, main = bootstrap_file in [initial_code_manager, initial_code_task]), both=False)
 
                     # Now link the code with the compilation manager structure
                     f.write("Node elem()\n", both=False)
@@ -243,19 +241,6 @@ def bootstrap():
                     f.write('Dict (__objects, "%s", elem)\n' % bootstrap_file, both=False)
                     f.write('Dict (elem, "initializers", %s_initial_IP)\n' % bootstrap_file, both=False)
 
-                    md5 = hashlib.md5()
-                    md5.update(open(bootstrap_file, 'r').read())
-
-                    f.write('Node hash_value("%s")\n' % md5.hexdigest(), both=False)
-                    f.write('Dict (elem, "hash_md5", hash_value)\n', both=False)
-
-                    f.write('Node __symbols()\n', both=False)
-                    f.write('Dict (elem, "symbols", __symbols)\n', both=False)
-
-                    for k, v in symbols.items():
-                        f.write('Node v(%s)\n' % v, both=False)
-                        f.write('Dict (__symbols, "%s", v)\n' % (k), both=False)
-
                 # Create code for initial task
                 print("[BOOT] task_manager")
                 f.write('Dict (task_frame, "IP", %s_initial_IP)\n' % (initial_code_manager), both=False)

+ 71 - 61
bootstrap/constructors.alc

@@ -7,21 +7,68 @@ include "modelling.alh"
 Element while_stack = ?
 Element variable_map = ?
 
-Element function construct_top():
+Element function construct_function():
 	String command
-	while (True):
+	Element result
+	Element main_function
+	Boolean continue
+	Element prev_element
+	Element first_element
+
+	// Initialize variables
+	prev_element = read_root()
+	main_function = read_root()
+
+	// Clear global variables
+	while_stack = create_node()
+	variable_map = create_node()
+
+	continue = True
+	while (continue):
 		command = input()
 		if (command == "global"):
-			return construct_global()!
+			result = construct_global()
 		elif (command == "funcdef"):
-			return construct_top_funcdef(False)!
+			result = construct_funcdef(False)
 		elif (command == "mutable_funcdef"):
-			return construct_top_funcdef(True)!
+			result = construct_funcdef(True)
 		else:
 			log("ERROR (1): did not understand command " + cast_e2s(command))
 			output("ERROR: compiled code not understood: " + cast_e2s(command))
 			return read_root()!
 
+		continue = input()
+		if (prev_element != read_root()):
+			dict_add_fast(prev_element, "next", result["start"])
+		else:
+			first_element = result["start"]
+
+		if (bool_and(element_eq(main_function, read_root()), command != "global")):
+			// In case no main function is defined, it is the first defined function
+			// This is mostly there to ensure backwards compatibility
+			main_function = result["instruction"]
+
+		prev_element = result["end"]
+
+		if (value_eq(result["name"], "main")):
+			// It was the function that we want to call
+			main_function = result["instruction"]
+
+	if (element_eq(main_function, read_root())):
+		log("ERROR (2): no main function found")
+		output("ERROR: no main function found")
+		return read_root()!
+
+	// Overwrite the main function with our declaration function
+	prev_element = main_function["body"]
+	log("Got main function V: " + cast_e2s(main_function))
+	log("Got main function S: " + dict_to_string(main_function))
+	dict_delete(main_function, "body")
+	dict_add_fast(main_function, "body", first_element)
+	dict_add_fast(result["end"], "next", prev_element)
+	
+	return main_function!
+
 Action function construct_global():
 	Action this_element
 	String declared_element
@@ -58,21 +105,25 @@ Action function construct_global():
 		dict_add_fast(value, "node", input())
 	dict_add_fast(assign, "value", value)
 
-	if (input()):
-		dict_add_fast(assign, "next", construct_top())
-	return this_element!
+	Element result
+	result = create_node()
+	dict_add_fast(result, "name", "")
+	dict_add_fast(result, "instruction", this_element)
+	dict_add_fast(result, "start", this_element)
+	dict_add_fast(result, "end", assign)
+	return result!
 
-Action function construct_top_funcdef(mutable : Boolean):
+Action function construct_funcdef(mutable : Boolean):
 	Action assign
 	Action resolve
 	Action constant
 	Element formal
 	Element func
 	Element params
-	Action global
+	Action declare
 	String name
 
-	global = create_value(!global)
+	declare = create_value(!global)
 	assign = create_value(!assign)
 	resolve = create_value(!resolve)
 	constant = create_value(!constant)
@@ -83,8 +134,8 @@ Action function construct_top_funcdef(mutable : Boolean):
 		formal = name
 	func = create_node()
 	params = create_node()
-	dict_add_fast(global, "var", formal)
-	dict_add_fast(global, "next", assign)
+	dict_add_fast(declare, "var", formal)
+	dict_add_fast(declare, "next", assign)
 	dict_add_fast(assign, "var", resolve)
 	dict_add_fast(assign, "value", constant)
 	dict_add_fast(resolve, "var", formal)
@@ -114,10 +165,13 @@ Action function construct_top_funcdef(mutable : Boolean):
 	// Now add the body
 	dict_add_fast(func, "body", construct_unknown())
 
-	if (input()):
-		dict_add_fast(assign, "next", construct_top())
-
-	return global!
+	Element result
+	result = create_node()
+	dict_add_fast(result, "name", name)
+	dict_add_fast(result, "instruction", func)
+	dict_add_fast(result, "start", declare)
+	dict_add_fast(result, "end", assign)
+	return result!
 
 Element function construct_unknown():
 	String elem
@@ -309,47 +363,3 @@ Action function construct_continue():
 	this_element = create_value(!continue)
 	dict_add_fast(this_element, "while", while_stack[list_len(while_stack) - 1])
 	return this_element!
-
-Action function construct_function():
-	Action func
-	Integer nrParams
-	Integer counter
-	Element param
-	Element params
-	String arg_names_decl
-	String inp
-
-	variable_map = create_node()
-
-	inp = input()
-	while (bool_and(inp != "funcdef", inp != "mutable_funcdef")):
-		// We skip over everything that is not a funcdef, as these are all just definitions of global stuff
-		inp = input()
-
-	// Consume the name
-	input()
-
-	params = create_node()
-	nrParams = input()
-	counter = 0
-	func = create_node()
-	arg_names_decl = "abcdefghijklmnopqrstuvwxyz"
-	dict_add_fast(func, "params", params)
-
-	if (inp == "mutable_funcdef"):
-		dict_add_fast(func, "mutable", create_node())
-
-	while (counter < nrParams):
-		param = create_node()
-		dict_add_fast(params, string_get(arg_names_decl, counter), param)
-		dict_add_fast(variable_map, input(), param)
-		// Output each parameter in turn
-		counter = counter + 1
-
-	// Now add the body
-	dict_add_fast(func, "body", construct_unknown())
-
-	// Consume the final 'false', to indicate that no additional code will come
-	input()
-
-	return func!

+ 0 - 75
bootstrap/modelling.alc

@@ -558,62 +558,6 @@ String function add_AL(model : Element, element : Element):
 
 	return reverseKeyLookup(model["model"], element)!
 
-Void function construct_model():
-	String command
-
-	while (True):
-		command = input()
-		if (command == "instantiate_bottom"):
-			Element m
-			m = instantiate_bottom()
-			dict_add_fast(global_models, input(), m)
-		elif (command == "add_node"):
-			model_add_node(global_models[input()], input())
-		elif (command == "add_value"):
-			model_add_value(global_models[input()], input(), input())
-		elif (command == "add_edge"):
-			model_add_edge(global_models[input()], input(), input(), input())
-		elif (command == "exit"):
-			return!
-		elif (command == "retype_model"):
-			retype_model(global_models[input()], global_models[input()])
-		elif (command == "retype"):
-			retype(global_models[input()], input(), input())
-		elif (command == "instantiate_model"):
-			Element m
-			m = instantiate_model(global_models[input()])
-			dict_add_fast(global_models, input(), m)
-		elif (command == "instantiate_node"):
-			instantiate_node(global_models[input()], input(), input())
-		elif (command == "instantiate_attribute"):
-			instantiate_attribute(global_models[input()], input(), input(), input())
-		elif (command == "instantiate_attribute_ref"):
-			instantiate_attribute_ref(global_models[input()], input(), input(), input())
-		elif (command == "instantiate_attribute_code"):
-			instantiate_attribute_code(global_models[input()], input(), input(), construct_function())
-		elif (command == "instantiate_link"):
-			instantiate_link(global_models[input()], input(), input(), input(), input())
-		elif (command == "model_define_attribute"):
-			model_define_attribute(global_models[input()], input(), input(), input(), input())
-		elif (command == "export_node"):
-			String local_name
-			String location
-			local_name = input()
-			location = input()
-			export_node(location, global_models[local_name])
-		elif (command == "import_node"):
-			Element m
-			command = input()
-			m = import_node(command)
-			if (element_eq(m, read_root())):
-				log("Error: import not found for " + command)
-			else:
-				dict_add_fast(global_models, input(), m)
-		elif (command == "add_code_model"):
-			add_code_model(global_models[input()], input(), construct_function())
-		else:
-			log("Modelling error: did not understand command " + command)
-
 Element function construct_model_raw(metamodel : Element):
 	String command
 	Element model
@@ -623,45 +567,26 @@ Element function construct_model_raw(metamodel : Element):
 	while (True):
 		command = input()
 		if (command == "add_node"):
-			input()
 			model_add_node(model, input())
 		elif (command == "add_value"):
-			input()
 			model_add_value(model, input(), input())
 		elif (command == "add_edge"):
-			input()
 			model_add_edge(model, input(), input(), input())
 		elif (command == "exit"):
 			return model!
 		elif (command == "instantiate_node"):
-			input()
 			instantiate_node(model, input(), input())
 		elif (command == "model_define_attribute"):
-			input()
 			model_define_attribute(model, input(), input(), input(), input())
 		elif (command == "instantiate_attribute"):
-			input()
 			instantiate_attribute(model, input(), input(), input())
 		elif (command == "instantiate_attribute_ref"):
-			input()
 			instantiate_attribute_ref(model, input(), input(), input())
 		elif (command == "instantiate_attribute_code"):
-			input()
 			instantiate_attribute_code(model, input(), input(), construct_function())
 		elif (command == "instantiate_link"):
-			input()
 			instantiate_link(model, input(), input(), input(), input())
-		elif (command == "import_node"):
-			input()
-			input()
-		elif (command == "export_node"):
-			input()
-			input()
-		elif (command == "instantiate_model"):
-			input()
-			input()
 		elif (command == "add_code_model"):
-			input()
 			add_code_model(model, input(), construct_function())
 		else:
 			log("Modelling error: did not understand command " + command)

+ 2 - 82
doc/actionlanguage.rst

@@ -6,12 +6,10 @@ This language serves as a nicer representation of the underlying Modelverse Grap
 The action language gets parsed by the parser, resulting in a kind of abstract syntax graph.
 This abstract syntax graph highly resembles an executable graph in the Modelverse Graph Language.
 
-Users will mainly use this language to write actions and constraints, but maybe also to implement their own interfaces, or override core functionality of the Modelverse.
+Users will mainly use this language to write actions and constraints, or even model operations.
 
 .. warning::
-   The current parser is unable to handle whitespaces in a general way.
-   As such, all indentation needs to be done using tabs, and the difference needs to be exactly 1.
-   This is different from Python, where tabs and whitespaces can be mixed, and the number can even vary.
+   The current action language compiler is rather basic and contains quite some problems.
 
 Files
 -----
@@ -236,81 +234,3 @@ User input and output is done through the keyworded operations *input()* and *ou
 
 All I/O is done using queues: the value is only read and written to a specific place in the Modelverse.
 To actually read or write it at the client side, these special places should be accessed through dedicated Modelverse operations.
-
-Examples
---------
-
-We now show some simple code fragments written in valid Action Language code.
-As this code is directly executable in the Modelverse, the main function is always called "main" and all includes are also present.
-We do not currently handle how to execute this code: this is explained further on.
-
-Fibonacci
-^^^^^^^^^
-
-The Fibonacci code is fairly simple.
-First, the primitives are imported to make sure that we know about all operations on primitives.
-Then, a function *fib* is defined, which will recursively compute the specified Fibonacci number.
-This is wrapped by a *main* function, which takes input from the user and outputs the result of the *fib* function.
-
-This code looks as follows::
-
-    include "primitives.alh"
-
-    Integer function fib(param : Integer):
-        if (param <= 2):
-            return 1!
-        else:
-            return fib(param - 1) + fib(param - 2)!
-
-    Void function main():
-        while(True):
-            output(fib(input()))
-        return!
-
-Factorial
-^^^^^^^^^
-
-Similarly, the code for computing a factorial is given below::
-
-    include "primitives.alh"
-
-    Integer function factorial(n : Integer):
-        if(n <= 1):
-            return 1!
-        else:
-            return n * factorial(n - 1)!
-
-    Void function main():
-        while(True):
-            output(factorial(input()))
-        return!
-
-Binary to decimal converter
-^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-A simple binary to decimal converter is given below::
-
-    include "primitives.alh"
-
-    Integer function b2d(param : String):
-        Integer value
-        value = 0
-        Integer length
-        length = string_len(param)
-        Integer counter
-        counter = integer_subtraction(length, 1)
-        Integer accumul
-        accumul = 1
-
-        while (counter >= 0):
-            if (string_get(param, counter) == "1"):
-                value = integer_addition(value, accumul)
-            accumul = integer_multiplication(accumul, 2)
-            counter = integer_subtraction(counter, 1)
-
-        return value!
-
-    Void function main():
-        while(True):
-            output(b2d(input()))
-        return!

+ 0 - 14
doc/advanced.rst

@@ -1,14 +0,0 @@
-Advanced examples
-=================
-
-These advanced examples show you how the core algorithms of the Modelverse are implemented and how you can potentially modify them.
-This part is still TODO, since this is probably not of interest to you.
-
-Inheritance Semantics
----------------------
-
-Instantiation Semantics
------------------------
-
-Conformance Semantics
----------------------

+ 0 - 99
doc/examples.rst

@@ -1,99 +0,0 @@
-Examples
-========
-
-To run this code, store it in a file (*e.g.*, test.alc), and execute the following commands::
-
-    python scripts/run_local_modelverse.py 8001 &
-    python scripts/make_parallel.py http://localhost:8001 test test.alc bootstrap/primitives.alc
-    python scripts/prompt.py
-
-In the prompt, log on to http://localhost:8001 as user *test*.
-Now, all input you send, will be caught in the *input()* calls seen in the code.
-Results will also be printed.
-
-Note that all content will, by default, be typed as string.
-If you want to send integers or so, prepend the input with a backslash (\\), which allows you to directly input the JSON code.
-For example, input *5* will be received as the string "5".
-To send the integer 5, the input should be *\\5*.
-
-Uploading a model, and using it, is very similar to what you usually do.
-The exception is that your model will be added before any code is executed.
-That way, you can just execute the same code, but include a model in it.
-
-The command for this is (instead of the *make_all.py* script)::
-
-    python scripts/execute_model.py http://localhost:8001 test bootstrap/*.alc integration/code/pn_interface.alc integration/code/rpgame.mvc
-
-This should **NOT** be used to upload all types of models during execution, as it will anonymously create the model.
-The model is only visible in the internals of the Modelverse, and not visible to any user, as it wasn't taken into account in the Modelverse Formalism Graph (in the MvC).
-
-Fibonacci Server
-----------------
-
-The first example is a simple Fibonacci server.
-The code is identical to the action language example from before, as this already included the *server* part (*i.e.*, the while loop).
-Now we will just connect to it using *prompt.py* and try out the code directly.
-
-The code is repeated below::
-
-    include "primitives.alh"
-
-    Integer function fib(param : Integer):
-        if (param <= 2):
-            return 1!
-        else:
-            return fib(param - 1) + fib(param - 2)!
-
-    Void function main():
-        while(True):
-            output(fib(input()))
-
-To run this code, save it to a file (*e.g.*, fibonacci.alc) and execute the following command::
-
-    python scripts/run_local_modelverse.py 8001
-    
-Now, the Modelverse is running, but we still need to upload our code.
-To compile the file, together with the primitives.alc file, execute the following command::
-
-    python scripts/make_parallel.py http://localhost:8001 test fibonacci.alc bootstrap/primitives.alc
-
-When this finishes, the Modelverse now stores a copy of our code in its own format.
-The Modelverse will automatically create the user *test* and start executing the *main* function as this user.
-We can therefore simply connect to the Modelverse as the *test* user and start seeing the responses.
-To start the prompt, execute the following command::
-
-    python scripts/prompt.py
-    
-In this prompt tool, you first have to configure the location of the Modelverse and the username.
-The defaults should be fine, so just press <return> twice.
-After that, you are in direct connection with the Modelverse.
-Each message you type in, is made available in the *input()* function of the code.
-Remember that, to send integers, you have to prefix this with a backslash (\\).
-To get, for example, the 1st Fibonacci number, type in the command::
-
-    \1
-
-You will now see the following.
-
-.. image:: img/prompt_fibonacci.png
-
-Since we are in an unconditional loop, you can send as many requests as you want, as long as they are understandable by the *fib* function.
-
-.. image:: img/prompt_fibonacci_more.png
-
-Inputting a string directly, such as *1* instead of *\\1*, will make the Modelverse crash on the execution of this code.
-This is normal, though in the future the Modelverse will keep running for other users: only the current user's code will be interrupted.
-
-Modelling Server
-----------------
-
-The simple Fibonacci server is not very relevant to the primary concern of the Modelverse: (meta-)modelling.
-But since we can create whatever kind of server we want, a simple (meta-)modelling server is created.
-The code offers an interface for users to execute modelling operations.
-The interface itself mostly just relays the incoming messages and operations to the internal modelling library.
-
-The full code is shown in the :download:`MvC Core Algorithm <../core/core_algorithm.alc>`.
-
-Its behaviour is not too complex, as it relays most operations to the library functions.
-Nonetheless, it implements most operations related to user access control and user management in general.
-When changes need to be made to the interface (*e.g.*, make it computer-readable instead of human-readable), only this file's output statements should be altered.

+ 5 - 114
doc/howto.rst

@@ -4,51 +4,7 @@ How to run
 Running the Modelverse is all done through the use of scripts to coordinate the three different projects.
 
 The following scripts are included by default.
-
-check_objects.py
-----------------
-
-Checks whether all compiled objects can be found, and if their symbol table does not contain undefined references.
-This script cannot be executed directly and is only a helper.
-
-compile.py
-----------
-
-Compiles the provided code with the selected mode.
-This should also not be called by end-tasks, though it is possible.
-
-Invocation::
-
-    python scripts/compile.py address file taskname object mode
-
-============== ====================================== =====================
-Parameter name Description                            Example              
-============== ====================================== =====================
-address        Address of the Modelverse              http://localhost:8001
-file           File to be compiled                    file.alc             
-taskname       Taskname to use when compiling         test_task            
-object         Object name to export to               object.o             
-mode           Either CO (constructors) or PO (graph) PO                   
-============== ====================================== =====================
-
-execute_model.py
-----------------
-
-Compile a model and action language files together, executing the action language.
-First, all models are added, and then the action language is executed, starting at function "main".
-Models being created are temporary, so they need to be exported before they can be accessed in the action language.
-
-Invocation::
-
-    python scripts/execute_model.py address taskname file1 file2 ...
-
-============== ======================================= =====================
-Parameter name Description                             Example
-============== ======================================= =====================
-address        Address of the Modelverse               http://localhost:8001
-taskname       Taskname to use when compiling          test
-file           File to compile (either .mvc or .alc)   test.alc
-============== ======================================= =====================
+Despite the various files, only *run_local_modelverse.py* is required for most cases.
 
 fix_files.py
 ------------
@@ -84,58 +40,6 @@ Invocation::
     
     python scripts/generate_bootstrap.py
 
-link_and_load.py
-----------------
-
-This takes a set of objects in the Modelverse, links them together in a single "executable" and executes it immediately.
-Generally not needed by end-tasks.
-
-Invocation::
-
-    python scripts/link_and_load.py address taskname object1 object2 ...
-
-============== ======================================= =====================
-Parameter name Description                             Example
-============== ======================================= =====================
-address        Address of the Modelverse               http://localhost:8001
-taskname       Taskname to use when compiling          test
-object         File to compile (either .mvc or .alc)   test.alc
-============== ======================================= =====================
-
-make_all.py
------------
-
-Compile a set of files and executes them immediately.
-
-Invocation::
-
-    python scripts/make_all.py address taskname file1 file2 ...
-
-============== ======================================= =====================
-Parameter name Description                             Example
-============== ======================================= =====================
-address        Address of the Modelverse               http://localhost:8001
-taskname       Taskname to use when compiling          test
-file           File to compile (either .mvc or .alc)   test.alc
-============== ======================================= =====================
-
-make_parallel.py
-----------------
-
-A parallel version of make_all.py.
-
-Invocation::
-
-    python scripts/make_parallel.py address taskname file1 file2 ...
-
-============== ======================================= =====================
-Parameter name Description                             Example
-============== ======================================= =====================
-address        Address of the Modelverse               http://localhost:8001
-taskname       Taskname to use when compiling          test
-file           File to compile (either .mvc or .alc)   test.alc
-============== ======================================= =====================
-
 prompt.py
 ---------
 
@@ -144,6 +48,8 @@ You can log in as a specific task and start sending input messages to the Modelv
 All output sent by the Modelverse will be printed in the console.
 There is no logic in the prompt itself, making it completely generic.
 
+While this is not the most usable way of communicating with the Modelverse, it provides a minimal interface.
+
 Invocation::
 
     python scripts/prompt.py
@@ -156,16 +62,12 @@ This combines MvK and MvS at the same system, and actually makes a direct link b
 While this is kind of a hack at the moment, it is really necessary for performance.
 To split them up, there just needs to be a statechart in between both of them (which is already written and working).
 
+The port option is optional, and defaults to 8001.
+
 Invocation::
 
     python scripts/run_local_modelverse.py port
 
-============== ============================== =======
-Parameter name Description                    Example
-============== ============================== =======
-port           Port to host the Modelverse on 8001
-============== ============================== =======
-
 run_tests.py
 ------------
 
@@ -174,14 +76,3 @@ Run the tests for all parts of the Modelverse.
 Invocation::
 
     python scripts/run_tests.py
-
-run_MvC_server.py
------------------
-
-Run the Modelverse with a modelling interface pre-loaded and fully operational.
-This is probably the only command you will need to start the Modelverse server on your local machine.
-You are advised to check the global variables of the script for all configuration parameters, such as the server port and the username and password of the root user.
-
-Invocation::
-
-    python scripts/run_MvC_server.py

+ 5 - 10
doc/index.rst

@@ -3,8 +3,8 @@
    You can adapt this file completely to your liking, but it should at least
    contain the root `toctree` directive.
 
-Welcome to Modelverse's documentation!
-======================================
+Welcome to the Modelverse documentation!
+========================================
 
 Contents:
 
@@ -12,15 +12,10 @@ Contents:
    :maxdepth: 2
     
    Installation <installation>
-   Modelverse components <components>
    How to run <howto>
+   Modelverse components <components>
    Action Language <actionlanguage>
    Modelling Language <modellanguage>
-   Examples <examples>
-   Advanced examples <advanced>
-   Modelverse core <mvc>
-   Mini modify <mini_modify>
+   Wrappers <wrappers>
    Common problems and solutions <problems>
-   Internal workings <internal>
-   Interface <interface>
-   Network communication models <communication_models>
+   Internals <internal>

+ 6 - 4
doc/installation.rst

@@ -1,7 +1,6 @@
 Installation
 ============
 
-
 Dependencies
 ------------
 
@@ -34,20 +33,23 @@ Tests
 -----
 
 To make sure that everything is working correctly, you can execute the tests with the script *scripts/run_tests.sh*.
-Total execution time is rather slow, even with all advanced performance optimizations (e.g., 1200 seconds on a i5-4570 using PyPy).
 
 Executing the tests is as simple as the following command::
 
     python scripts/run_tests.py
 
 This will run a set of tests for all different projects.
+Note that this also causes some bootstrap files to be created, which might take some time on slow machines.
+A faster alternative is to only run the overall tests::
+
+    python -m pytest integration
 
 PyPy
 ^^^^
 
 The default way of executing tests is probably through CPython.
-Note, however, that CPython is a very slow implementation of Python, which makes everything in the Modelverse slower.
-While it is not impossible to use CPython, using PyPy is highly recommended for the server!
+Note, however, that CPython is a slow implementation of Python, which makes everything in the Modelverse slower.
+While it is not impossible to use CPython, using PyPy is recommended for the server!
 Nonetheless, PyPy is often not the default interpreter.
 You will therefore have to explicitly give control to PyPy instead of CPython.
 

+ 10 - 17
doc/internal.rst

@@ -25,13 +25,6 @@ The Modelverse graph is then stored in RDF representation and all operations on
 Due to this level of indirection, performance is extremely slow.
 To increase performance, we would likely have to make more *composite* operations, or even group different requests together internally.
 
-Status codes
-^^^^^^^^^^^^
-
-The MvS returns, apart from its actual return value, a status code for the request.
-This value is not used by the MvK at all, since sometimes a request is expected to give an error (*e.g.*, checking whether an element is present).
-When debugging the MvS, however, these status codes can come in handy.
-
 Modelverse Kernel
 -----------------
 
@@ -101,6 +94,16 @@ Whereas primitives are required for a functional Modelverse, precompiled functio
 This is interesting, since with precompiled functions, no intermediate values will be visible.
 Additionally, precompiled functions cannot be changed, as they are Python code instead of being explicitly modelled.
 
+Modelling operations
+^^^^^^^^^^^^^^^^^^^^
+
+Apart from the simple action language interpreter presented before, the Modelverse State is loaded with modelling logic.
+This includes common functions, such as conformance checking, model transformation, and instantiation.
+As the code is loaded in the MvS by default, the MvK will automatically start executing that code.
+Therefore, most users will only experience the Modelverse as a modelling environment.
+Nonetheless, the Modelverse Kernel is more generic than this, and would also allow for users to define their own interface.
+As all aspects of the Modelverse are explicitly modelled, it is possible to alter the pre-loaded model and thus update the built-in behaviour.
+
 Modelverse Interface
 --------------------
 
@@ -139,16 +142,6 @@ This is bad if the interface suddenly accepts new keywords or removes support fo
 During the execution of the visitor, it would already be possible to start transmitting the list to the Modelverse, such that the Modelverse can create the code in parallel with the actual parsing.
 While this is possible, we currently split this up in different phases: first the list is generated completely, and then it is transferred to the Modelverse in a single request.
 
-Primitives visitor
-^^^^^^^^^^^^^^^^^^
-
-The primitives visitor generates a Modelverse graph directly.
-Its use is deprecated, as the constructors are much more elegant.
-While direct use of this visitor is not recommended, except for performance reasons, the bootstrap visitor (discussed next) is based on this visitor.
-
-This visitor creates a serialized version of the graph and transmits it to the Modelverse.
-The Modelverse has a built-in primitive to decode this graph and store it.
-
 Bootstrap visitor
 ^^^^^^^^^^^^^^^^^
 

+ 39 - 12
doc/modellanguage.rst

@@ -4,7 +4,7 @@ Modelling Language
 Apart from the action language, the Modelverse also has a modelling language.
 With this language, models (*i.e.*, data) can be defined in addition to the algorithms.
 
-This language is still mostly work in progress, but should be decent enough to construct simple metamodels and instantiate them.
+This language is still work in progress, but should be decent enough to construct simple metamodels and instantiate them.
 All models have the extension \*.mvc, indicating that they are models and should be compiled as such.
 
 If you want to create models interactively, such as with another tool, it is strongly recommended to use the interactive interface to do this, as the modelling language is completely static.
@@ -16,21 +16,14 @@ The modelling language defines data structures, which will be formed as models i
 
 Several constructs are supported.
 
-Import
-^^^^^^
-
-An import pulls in a model and makes it accessible using a simpler identifier.
-The structure is as follows::
-
-    import path/in/modelverse as my_model
-
-After this import, the model that was previously exported to *path/in/modelverse* becomes available as *my_model*.
-
 Include
 ^^^^^^^
 
-When combined with action language, the action language might require some includes of header files.
+When combined with action language, for example with code fragments, the action language might require some includes of header files.
 To do this, the includes can be placed at the top of the hierarchy.
+The structure is as follows::
+
+        include "primitives.alh"
 
 Model
 ^^^^^
@@ -38,6 +31,15 @@ Model
 Every model is defined by first specifying the type of model to instantiate, followed by the name of the model to create.
 The name of the model can then later on be referenced in other models (as type, or for exporting).
 Within the model, all names of the type model can be used as types again.
+This is only used internally for bootstrapping purposes, so feel free to write whatever you want here.
+
+The structure is as follows::
+
+        SimpleClassDiagrams PetriNets{
+                ...
+        }
+
+All further operations happen inside such a definition.
 
 Instance
 ^^^^^^^^
@@ -45,6 +47,14 @@ Instance
 A model consists of some instances.
 These instances are instances of types specified by the model that is the metaclass of the current model.
 
+The structure is as follows::
+
+        SimpleClassDiagrams PetriNets {
+                Class Place {
+                        ...
+                }
+        }
+
 Attribute
 ^^^^^^^^^
 
@@ -180,3 +190,20 @@ Use in interactive interface
 
 The interactive interface, such as the *prompt.py* script, can also invoke the model compiler.
 In this case, however, the import, export, and model type and model name parameters are ignored as they have to be defined and checked in the bigger context of the MvC.
+
+Internal use only
+-----------------
+
+Some constructs only make sense in the context of the bootstrap generation.
+These constructs can still be used at all times, but are meaningless.
+
+Import
+^^^^^^
+
+An import pulls in a model and makes it accessible using a simpler identifier.
+The structure is as follows::
+
+    import path/in/modelverse as my_model
+
+After this import, the model that was previously exported to *path/in/modelverse* becomes available as *my_model*.
+

+ 0 - 2
doc/upload.sh

@@ -1,2 +0,0 @@
-#!/bin/bash
-rsync -v --progress --recursive _build/html/* yentl@msdl.uantwerpen.be:/var/www/msdl/documentation/modelverse/

+ 175 - 118
hybrid_server/classes/mvkcontroller.xml

@@ -1,6 +1,7 @@
 <class name="MvKController">
     <relationships>
         <association name="to_mvi" class="Server" min="1" max="1"/>
+        <association name="tasks" class="Task"/>
     </relationships>
     <constructor>
         <parameter name="params"/>
@@ -9,6 +10,7 @@
             self.mvs = ModelverseState("../bootstrap/bootstrap.m.gz")
             # Enable Garbage Collection
             self.mvs.GC = True
+
             self.root = self.mvs.read_root()
 
             # Instantiate the kernel.
@@ -65,20 +67,14 @@
                 else:
                     print("warning: unknown kernel option '%s'." % opt)
 
-            self.all_failed = False
-            self.timeout = False
+            self.port = int(sys.argv[1])
 
-            self.tasks = set()
+            self.sc_map = {}
+            self.forward = None
+            self.HTTP_reply = None
             self.input_queue = defaultdict(list)
             self.output_queue = defaultdict(list)
-            self.source = None
-            self.port = int(sys.argv[1])
-            self.count = 0
             
-            self.debugged_tasks = set()
-            self.debug_info = {}
-            self.done_something = False
-
             self.mvs_operations = {
                     "CN": self.mvs.create_node,
                     "CE": self.mvs.create_edge,
@@ -148,121 +144,133 @@
         </state>
 
         <parallel id="running">
+            <state id="forward_inputs">
+                <state id="forward">
+                    <transition cond="set(self.input_queue) &amp; set(self.sc_map)" target=".">
+                        <script>
+                            self.input_task = (set(self.input_queue) &amp; set(self.sc_map)).pop()
+                            value = self.input_queue[self.input_task].pop(0)
+                            if not self.input_queue[self.input_task]:
+                                del self.input_queue[self.input_task]
+                        </script>
+                        <raise event="input" scope="narrow" target="self.sc_map[self.input_task]">
+                            <parameter expr="value"/>
+                        </raise>
+                    </transition>
+                </state>
+            </state>
+
+            <state id="forward_outputs">
+                <state id="forward">
+                    <transition cond="set(self.output_queue) &amp; set(self.sc_map)" target=".">
+                        <script>
+                            self.output_task = (set(self.output_queue) &amp; set(self.sc_map)).pop()
+                            value = self.output_queue[self.output_task].pop(0)
+                            if not self.output_queue[self.output_task]:
+                                del self.output_queue[self.output_task]
+                        </script>
+                        <raise event="output" scope="narrow" target="self.sc_map[self.output_task]">
+                            <parameter expr="value"/>
+                        </raise>
+                    </transition>
+                </state>
+            </state>
+
             <state id="wait_for_requests">
                 <state id="wait">
                     <transition event="from_mvi" target=".">
                         <parameter name="source"/>
                         <parameter name="data"/>
                         <script>
+                            self.source = source
                             # No JSON encoding necessary, as it is not complex
                             try:
-                                self.done_something = False
                                 if data["op"] == "set_input":
                                     if "value" in data:
                                         value = [json.loads(data["value"])]
                                     else:
                                         value = json.loads(data["data"])
-                                    self.input_queue[data["taskname"]].append((source, value))
+                                    self.forward = (data["taskname"], "input", value)
+                                    self.HTTP_reply = "OK"
                                 elif data["op"] == "get_output":
-                                    self.output_queue[data["taskname"]].append(source)
-                                elif data["op"] == "attach_debugger":
-                                    self.debugged_tasks.add(data["taskname"])
-                                    self.done_something = True
-                                    self.source = source
-                                    self.debug_info[data["taskname"]] = {'state': 'running', 'breakpoints': []}
-                                elif data["op"] == "detach_debugger":
-                                    self.debugged_tasks.discard(data["taskname"])
-                                    self.done_something = True
-                                    self.source = source
-                                    del self.debug_info[data["taskname"]]
+                                    self.forward = (data["taskname"], "output", self.source)
+                                    self.HTTP_reply = None
                                 elif data["op"] == "pause":
-                                    if data["taskname"] in self.debugged_tasks:
-                                        self.debug_info[data["taskname"]]['state'] = 'paused'
-                                    self.done_something = True
-                                    self.source = source
+                                    #TODO
+                                    self.HTTP_reply = "NotImplemented"
                                 elif data["op"] == "resume":
-                                    if data["taskname"] in self.debugged_tasks:
-                                        self.debug_info[data["taskname"]]['state'] = 'running'
-                                    self.done_something = True
-                                    self.source = source
-                                elif data["op"] == "step_over":
-                                    pass
-                                    self.done_something = True
-                                    self.source = source
-                                elif data["op"] == "step_into":
-                                    pass
-                                    self.done_something = True
-                                    self.source = source
+                                    #TODO
+                                    self.HTTP_reply = "NotImplemented"
                                 else:
-                                    raise Exception("DROPPING unknown operation: " + str(data["op"]))
-                            except ValueError:
-                                print("Error when deserializing request: " + str(data))
-                                raise
+                                    self.HTTP_reply = "Unknown command: %s" % data["op"]
+                            except ValueError as e:
+                                self.HTTP_reply = "Error when deserializing request: %s" % traceback.format_exc()
+                            except Exception as e:
+                                self.HTTP_reply = "Unknown Modelverse Error: %s" % traceback.format_exc()
                         </script>
                     </transition>
 
-                    <transition cond="self.done_something" target=".">
+                    <transition cond="not self.forward and self.HTTP_reply is not None" target=".">
                         <raise event="HTTP_input" scope="narrow" target="'to_mvi/%s' % self.source">
-                            <parameter expr="json.dumps(True)"/>
+                            <parameter expr="json.dumps(self.HTTP_reply)"/>
                         </raise>
                         <script>
-                            self.done_something = False
+                            self.HTTP_reply = None
+                            self.forward = None
                         </script>
                     </transition>
-                </state>
-            </state>
 
-            <state id="execution" initial="execution">
-                <state id="execution">
-                    <onentry>
+                    <transition cond="self.forward and self.forward[1] == 'input' and self.forward[0] in self.sc_map" target=".">
+                        <raise event="input" scope="narrow" target="self.sc_map[self.forward[0]]">
+                            <parameter expr="self.forward[2]"/>
+                        </raise>
+                        <raise event="HTTP_input" scope="narrow" target="'to_mvi/%s' % self.source">
+                            <parameter expr="json.dumps(self.HTTP_reply)"/>
+                        </raise>
                         <script>
-                            #start = time.time()
-                            self.outputs = []
-                            self.timeout = False
-                            if self.tasks:
-                                task = self.tasks.pop()
-                                if not task in self.debugged_tasks or self.debug_info[task]['state'] == 'running':
-                                    # Check if there are values to input
-                                    while self.input_queue[task]:
-                                        source, args = self.input_queue[task].pop(0)
-                                        for args_entry in args:
-                                            self.execute_modelverse(task, "set_input", [args_entry])
-
-                                        self.outputs.append((source, "OK"))
-                                        self.all_failed = False
-
-                                    if task in self.debugged_tasks:
-                                        start_time = -float('inf')
-                                    else:
-                                        start_time = time.time()
-                                    # Grant each task some milliseconds of execution
-                                    while (time.time() - start_time &lt; 0.05):
-                                        self.execute_modelverse(task, "execute_rule", [])
+                            self.HTTP_reply = None
+                            self.forward = None
+                        </script>
+                    </transition>
 
-                                        if not self.mvk.success:
-                                            # Blocking or broken, so quit already to stop wasting CPU
-                                            break
+                    <transition cond="self.forward and self.forward[1] == 'input' and self.forward[0] not in self.sc_map" target=".">
+                        <raise event="HTTP_input" scope="narrow" target="'to_mvi/%s' % self.source">
+                            <parameter expr="json.dumps(self.HTTP_reply)"/>
+                        </raise>
+                        <script>
+                            self.input_queue[self.forward[0]].append(self.forward[2])
+                            self.HTTP_reply = None
+                            self.forward = None
+                        </script>
+                    </transition>
 
-                                        # Could at least execute one instruction, so mark it as "not failed"
-                                        self.all_failed = False
+                    <transition cond="self.forward and self.forward[1] == 'output' and self.forward[0] in self.sc_map" target=".">
+                        <raise event="output" scope="narrow" target="self.sc_map[self.forward[0]]">
+                            <parameter expr="self.forward[2]"/>
+                        </raise>
+                        <script>
+                            self.HTTP_reply = None
+                            self.forward = None
+                        </script>
+                    </transition>
 
-                                    # Perform output if there is anything
-                                    while self.output_queue[task]:
-                                        self.execute_modelverse(task, "get_output", [])
-                                        if self.mvk.success:
-                                            self.outputs.append((self.output_queue[task].pop(0), self.mvk.returnvalue))
-                                            self.all_failed = False
-                                        else:
-                                            break
+                    <transition cond="self.forward and self.forward[1] == 'output' and self.forward[0] not in self.sc_map" target=".">
+                        <script>
+                            self.output_queue[self.forward[0]].append(self.forward[2])
+                            self.HTTP_reply = None
+                            self.forward = None
+                        </script>
+                    </transition>
+                </state>
+            </state>
 
-                            else:
-                                if self.count >= 2000:
-                                    self.count = 0
-                                    self.mvs.purge()
-                                else:
-                                    self.count += 1
-                                    self.mvs.garbage_collect()
+            <parallel id="execution">
+                <state id="refresh_tasks" initial="refresh_tasks">
+                    <state id="refresh_tasks">
+                        <onentry>
+                            <script>
                                 out = self.mvs.read_outgoing(self.root)
+                                tasks = set()
                                 for m in out:
                                     src, task = self.mvs.read_edge(m)
                                     outgoing = self.mvs.read_outgoing(m)
@@ -271,38 +279,87 @@
                                     name = self.mvs.read_value(dest)
                                     if name.startswith("__"):
                                         continue
-                                    self.tasks.add(name)
-                                self.timeout = self.all_failed
-                                self.all_failed = True
-                        </script>
-                    </onentry>
+                                    tasks.add(name)
 
-                    <transition cond="self.outputs" target="../process_data"/>
-                    <transition cond="not self.timeout and not self.outputs" target="../timeout_none"/>
-                    <transition cond="self.timeout and not self.outputs" target="../timeout_long"/>
-                </state>
+                                self.new_tasks = set([i for i in tasks if i not in self.sc_map])
+                                self.old_tasks = set([i for i in self.sc_map if i not in tasks])
+                            </script>
+                        </onentry>
 
-                <state id="timeout_long">
-                    <transition after="self.sccd_yield() + 0.05" target="../execution"/>
-                </state>
+                        <transition cond="self.new_tasks" target="../create_SC"/>
+                        <transition cond="not self.new_tasks and self.old_tasks" target="../remove_SC"/>
+                        <transition after="1" target="."/>
+                    </state>
+
+                    <state id="create_SC" initial="creating">
+                        <state id="creating">
+                            <onentry>
+                                <script>
+                                    self.task = self.new_tasks.pop()
+                                </script>
+                                <raise event="create_instance" scope="cd">
+                                    <parameter expr="'tasks'"/>
+                                    <parameter expr="'Task'"/>
+                                    <parameter expr="self.task"/>
+                                    <parameter expr="self.mvs_operations"/>
+                                    <parameter expr="self.mvk"/>
+                                </raise>
+                            </onentry>
+
+                            <transition event="instance_created" target="../created">
+                                <parameter name="instancename"/>
+                                <raise scope="cd" event="start_instance">
+                                    <parameter expr="instancename" />
+                                </raise>
+                                <script>
+                                    self.sc_map[self.task] = instancename
+                                </script>
+                            </transition>
+                        </state>
+                        <state id="created">
+                            <transition cond="self.new_tasks" target="../creating"/>
+                            <transition cond="not self.new_tasks and self.old_tasks" target="../../remove_SC"/>
+                            <transition cond="not self.new_tasks and not self.old_tasks" target="../../refresh_tasks"/>
+                        </state>
+                    </state>
+
+                    <state id="remove_SC">
+                        <transition cond="self.old_tasks" target=".">
+                            <script>
+                                task = self.old_tasks.pop()
+                            </script>
+                            <raise scope="cd" event="delete_instance">
+                                <parameter expr="self.sc_map[task]"/>
+                            </raise>
+                            <script>
+                                del self.sc_map[task]
+                            </script>
+                        </transition>
 
-                <state id="timeout_none">
-                    <transition after="self.sccd_yield()" target="../execution"/>
+                        <transition cond="not self.old_tasks" target="../refresh_tasks"/>
+                    </state>
                 </state>
 
-                <state id="process_data">
-                    <transition cond="self.outputs" target=".">
-                        <script>
-                            destination, value = self.outputs.pop()
-                        </script>
-                        <raise event="HTTP_input" scope="narrow" target="'to_mvi/%s' % destination">
-                            <parameter expr="json.dumps(value)"/>
-                        </raise>
-                    </transition>
+                <state id="mvs_GC" initial="suspend_tasks">
+                    <state id="suspend_tasks">
+                        <onentry>
+                            <raise scope="broad" event="pause_task"/>
+                        </onentry>
+
+                        <transition target="../mvs_GC"/>
+                    </state>
 
-                    <transition cond="not self.outputs" target="../execution"/>
+                    <state id="mvs_GC">
+                        <onentry>
+                            <script>
+                                self.mvs.garbage_collect()
+                            </script>
+                            <raise scope="broad" event="resume_task"/>
+                        </onentry>
+                        <transition after="self.sccd_yield() + 10" target="."/>
+                    </state>
                 </state>
-            </state>
+            </parallel>
 
             <state id="remove_sockets">
                 <state id="remove_sockets">

+ 146 - 0
hybrid_server/classes/task.xml

@@ -0,0 +1,146 @@
+<class name="Task">
+    <relationships>
+        <association name="parent" class="MvKController" min="1" max="1"/>
+    </relationships>
+    <constructor>
+        <parameter name="taskname"/>
+        <parameter name="mvs_operations"/>
+        <parameter name="mvk"/>
+        <body>
+            <![CDATA[
+            self.taskname = taskname
+            self.mvs_operations = mvs_operations
+            self.mvk = mvk
+
+            self.failed = False
+            self.output_queue = []
+            self.outputs = []
+            self.do_yield = False
+            ]]>
+        </body>
+
+    </constructor>
+
+    <method name="execute_modelverse">
+        <parameter name="taskname"/>
+        <parameter name="operation"/>
+        <parameter name="params"/>
+        <body>
+            <![CDATA[
+            reply = None
+            commands = []
+            mvk = self.mvk
+            mvs_operations = self.mvs_operations
+            try:
+                while 1:
+                    commands = mvk.execute_yields(taskname, operation, params, reply)
+                    if commands is None:
+                        break
+                    reply = [mvs_operations[command[0]](*(command[1])) for command in commands]
+            except:
+                print("ERROR: " + str(self.mvk.debug_info.get(taskname, "Unknown taskname")))
+                #TODO delete self, as the task has crashed!
+                return False
+            return True
+            ]]>
+        </body>
+    </method>
+
+    <scxml initial="start">
+        <parallel id="start">
+            <state id="execution" initial="running">
+                <state id="running" initial="executing">
+                    <transition event="pause_task" target="../suspended"/>
+
+                    <state id="executing">
+                        <onentry>
+                            <script>
+                                start_time = time.time()
+                                # Grant each task some milliseconds of execution
+                                self.do_yield = False
+                                while (time.time() - start_time &lt; 0.05):
+                                    if not self.execute_modelverse(self.taskname, "execute_rule", []):
+                                        # Failed!
+                                        self.failed = True
+                                        break
+
+                                    if not self.mvk.success:
+                                        # Blocking or broken, so quit already to stop wasting CPU
+                                        self.do_yield = True
+                                        break
+
+                                if not self.failed:
+                                    # Perform output if there is anything
+                                    while self.output_queue:
+                                        if self.execute_modelverse(self.taskname, "get_output", []):
+                                            if self.mvk.success:
+                                                self.outputs.append((self.output_queue.pop(0), self.mvk.returnvalue))
+                                            else:
+                                                # No output left in Mv, so break
+                                                break
+                                        else:
+                                            self.failed = True
+                                            break
+                            </script>
+                        </onentry>
+
+                        <transition cond="self.failed" target="../../failed"/>
+                        <transition after="self.sccd_yield()" target="."/>
+                        <transition cond="self.do_yield" target="../yielded"/>
+                    </state>
+
+                    <state id="yielded">
+                        <transition after="self.sccd_yield() + 1" target="../executing"/>
+                        <transition event="processed_input" target="../executing"/>
+                        <transition event="waiting_output" target="../executing"/>
+                    </state>
+                </state>
+
+                <state id="suspended">
+                    <state id="suspended">
+                        <transition event="resume" target="../../running"/>
+                    </state>
+                </state>
+
+                <state id="failed">
+                    <state id="failed">
+                        <!-- TODO delete task -->
+                    </state>
+                </state>
+            </state>
+
+            <state id="process_events">
+                <state id="process_events">
+                    <transition event="input" target=".">
+                        <parameter name="params"/>
+                        <script>
+                            for args_entry in params:
+                                if not self.execute_modelverse(self.taskname, "set_input", [args_entry]):
+                                    # Failed!
+                                    self.failed = True
+                                    break
+                        </script>
+                        <raise event="processed_input"/>
+                    </transition>
+
+                    <transition event="output" target=".">
+                        <parameter name="params"/>
+                        <script>
+                            self.output_queue.append(params)
+                        </script>
+                        <raise event="waiting_output"/>
+                    </transition>
+
+                    <transition cond="self.outputs" target=".">
+                        <script>
+                            source, value = self.outputs.pop(0)
+                        </script>
+                        <raise event="HTTP_input" scope="narrow" target="'parent/to_mvi/%s' % source">
+                            <parameter expr="json.dumps(value)"/>
+                        </raise>
+                    </transition>
+                </state>
+            </state>
+        </parallel>
+    </scxml>
+</class>

+ 1 - 0
hybrid_server/server.xml

@@ -28,4 +28,5 @@
     <class src="classes/mvkcontroller.xml" default="true"/>
     <class src="classes/server.xml"/>
     <class src="classes/socket.xml"/>
+    <class src="classes/task.xml"/>
 </diagram>

+ 47 - 52
integration/code/cbd_design.mvc

@@ -1,61 +1,56 @@
-import models/SimpleClassDiagrams as SCD
 include "primitives.alh"
 
-SCD CausalBlockDiagrams_Design{
-    SimpleAttribute Float {
-        constraint = $
-            String function constraint(model : Element, name : String):
-                if (bool_not(is_physical_float(model["model"][name]))):
-                    return "Float has no float value"!
-                else:
-                    return "OK"!
-            $
-    }
-
-    SimpleAttribute String {
-        constraint = $
-            String function constraint(model : Element, name : String):
-                if (bool_not(is_physical_string(model["model"][name]))):
-                    return "String has no string value"!
-                else:
-                    return "OK"!
-            $
-    }
+SimpleAttribute Float {
+    constraint = $
+        String function constraint(model : Element, name : String):
+            if (bool_not(is_physical_float(model["model"][name]))):
+                return "Float has no float value"!
+            else:
+                return "OK"!
+        $
+}
 
-    Class Block{}
-    Class ICBlock{}
+SimpleAttribute String {
+    constraint = $
+        String function constraint(model : Element, name : String):
+            if (bool_not(is_physical_string(model["model"][name]))):
+                return "String has no string value"!
+            else:
+                return "OK"!
+        $
+}
 
-    Class ConstantBlock{
-        value : Float
-    }
+Class Block{}
+Class ICBlock{}
 
-    Class AdditionBlock{}
-    Class NegatorBlock{}
-    Class MultiplyBlock{}
-    Class InverseBlock{}
-    Class DelayBlock{}
-    Class IntegratorBlock{}
-    Class DerivatorBlock{}
-    Class ProbeBlock{
-        name : String
-    }
+Class ConstantBlock{
+    value : Float
+}
 
-    Association Link(Block, Block){}
-    Association InitialCondition(Block, ICBlock){
-        source_lower_cardinality = 1
-        source_upper_cardinality = 1
-    }
+Class AdditionBlock{}
+Class NegatorBlock{}
+Class MultiplyBlock{}
+Class InverseBlock{}
+Class DelayBlock{}
+Class IntegratorBlock{}
+Class DerivatorBlock{}
+Class ProbeBlock{
+    name : String
+}
 
-    Inheritance (ConstantBlock, Block){}
-    Inheritance (AdditionBlock, Block){}
-    Inheritance (NegatorBlock, Block){}
-    Inheritance (MultiplyBlock, Block){}
-    Inheritance (InverseBlock, Block){}
-    Inheritance (ProbeBlock, Block){}
-    Inheritance (ICBlock, Block){}
-    Inheritance (DelayBlock, ICBlock){}
-    Inheritance (IntegratorBlock, ICBlock){}
-    Inheritance (DerivatorBlock, ICBlock){}
+Association Link(Block, Block){}
+Association InitialCondition(Block, ICBlock){
+    source_lower_cardinality = 1
+    source_upper_cardinality = 1
 }
 
-export CausalBlockDiagrams_Design to models/CausalBlockDiagrams_Design
+Inheritance (ConstantBlock, Block){}
+Inheritance (AdditionBlock, Block){}
+Inheritance (NegatorBlock, Block){}
+Inheritance (MultiplyBlock, Block){}
+Inheritance (InverseBlock, Block){}
+Inheritance (ProbeBlock, Block){}
+Inheritance (ICBlock, Block){}
+Inheritance (DelayBlock, ICBlock){}
+Inheritance (IntegratorBlock, ICBlock){}
+Inheritance (DerivatorBlock, ICBlock){}

+ 0 - 77
integration/code/cbd_runtime.mvc

@@ -1,77 +0,0 @@
-import models/SimpleClassDiagrams as SCD
-include "primitives.alh"
-
-SCD CausalBlockDiagrams_Runtime{
-    AttributeValue Float {
-        constraint = $
-            String constraint(model : Element, name : String):
-                if (bool_not(is_physical_float(model["model"][name]))):
-                    return "Float has no float value"!
-                else:
-                    return "OK"!
-            $
-    }
-
-    AttributeValue String {
-        constraint = $
-            String constraint(model : Element, name : String):
-                if (bool_not(is_physical_string(model["model"][name]))):
-                    return "String has no string value"!
-                else:
-                    return "OK"!
-            $
-    }
-
-    Class Block{
-        signal : Float
-    }
-    Class ICBlock{
-        last_in : Float
-    }
-
-    Class ConstantBlock{
-        value : Float
-    }
-
-    Class ProbeBlock{
-        name : String
-    }
-
-    Class AdditionBlock{}
-    Class NegatorBlock{}
-    Class MultiplyBlock{}
-    Class InverseBlock{}
-    Class DelayBlock{}
-    Class IntegratorBlock{
-        last_out? : Float
-    }
-
-    Class DerivatorBlock{}
-    Class Time{
-        lower_cardinality = 1
-        upper_cardinality = 1
-
-        start_time : Float
-        current_time : Float
-    }
-
-    Association Link(Block, Block){
-    }
-    Association InitialCondition(Block, ICBlock){
-        source_lower_cardinality = 0
-        source_upper_cardinality = 1
-    }
-
-    Inheritance (ConstantBlock, Block){}
-    Inheritance (AdditionBlock, Block){}
-    Inheritance (NegatorBlock, Block){}
-    Inheritance (MultiplyBlock, Block){}
-    Inheritance (InverseBlock, Block){}
-    Inheritance (ICBlock, Block){}
-    Inheritance (DelayBlock, ICBlock){}
-    Inheritance (DerivatorBlock, ICBlock){}
-    Inheritance (IntegratorBlock, ICBlock){}
-    Inheritance (ProbeBlock, Block){}
-}
-
-export CausalBlockDiagrams_Runtime to models/CausalBlockDiagrams_Runtime

+ 0 - 654
integration/code/cbd_semantics.alc

@@ -1,654 +0,0 @@
-include "primitives.alh"
-include "modelling.alh"
-include "object_operations.alh"
-include "library.alh"
-include "conformance_scd.alh"
-include "io.alh"
-include "metamodels.alh"
-include "compilation_manager.alh"
-
-Element function retype_to_runtime(design_model : Element):
-	Element runtime_model
-	Element all_blocks
-	Element all_links
-	String mm_type_name
-	String element_name
-	String attr_name
-	String attr_value
-	String attribute
-	String src
-	String dst
-	String time
-	Element all_attributes
-
-	runtime_model = instantiate_model(import_node("models/CausalBlockDiagrams_Runtime"))
-
-	all_blocks = allInstances(design_model, "Block")
-	while (list_len(all_blocks) > 0):
-		element_name = set_pop(all_blocks)
-		mm_type_name = reverseKeyLookup(design_model["metamodel"]["model"], dict_read_node(design_model["type_mapping"], design_model["model"][element_name]))
-		element_name = instantiate_node(runtime_model, mm_type_name, element_name)
-		if (is_nominal_instance(design_model, element_name, "ConstantBlock")):
-			instantiate_attribute(runtime_model, element_name, "value", read_attribute(design_model, element_name, "value"))
-		elif (is_nominal_instance(design_model, element_name, "ProbeBlock")):
-			instantiate_attribute(runtime_model, element_name, "name", read_attribute(design_model, element_name, "name"))
-
-	// Don't merge this together with the block conversion, as the destination block might not exist yet!
-	all_links = allInstances(design_model, "Link")
-	while (read_nr_out(all_links) > 0):
-		element_name = set_pop(all_links)
-		src = reverseKeyLookup(design_model["model"], read_edge_src(design_model["model"][element_name]))
-		dst = reverseKeyLookup(design_model["model"], read_edge_dst(design_model["model"][element_name]))
-		instantiate_link(runtime_model, "Link", element_name, src, dst)
-
-	all_links = allInstances(design_model, "InitialCondition")
-	while (read_nr_out(all_links) > 0):
-		element_name = set_pop(all_links)
-		src = reverseKeyLookup(design_model["model"], read_edge_src(design_model["model"][element_name]))
-		dst = reverseKeyLookup(design_model["model"], read_edge_dst(design_model["model"][element_name]))
-		instantiate_link(runtime_model, "InitialCondition", element_name, src, dst)
-
-	return runtime_model!
-
-Element function sanitize(new_runtime_model : Element, old_runtime_model : Element):
-	Element all_blocks
-	Element all_links
-	String element_name
-	String attr_name
-	String attr_value
-	String attribute
-	String time
-	Element all_attributes
-	Float current_time
-
-	all_blocks = allInstances(new_runtime_model, "Block")
-	while (list_len(all_blocks) > 0):
-		element_name = set_pop(all_blocks)
-		if (dict_in(old_runtime_model["model"], element_name)):
-			if (is_nominal_instance(new_runtime_model, element_name, "ICBlock")):
-				instantiate_attribute(new_runtime_model, element_name, "last_in", read_attribute(old_runtime_model, element_name, "last_in"))
-			if (is_nominal_instance(new_runtime_model, element_name, "IntegratorBlock")):
-				instantiate_attribute(new_runtime_model, element_name, "last_out", read_attribute(old_runtime_model, element_name, "last_out"))
-			instantiate_attribute(new_runtime_model, element_name, "signal", read_attribute(old_runtime_model, element_name, "signal"))
-		else:
-			instantiate_attribute(new_runtime_model, element_name, "signal", 0.0)
-
-	if (dict_in(old_runtime_model["model"], "time")):
-		current_time = read_attribute(old_runtime_model, "time", "current_time")
-	else:
-		current_time = 0
-
-	time = instantiate_node(new_runtime_model, "Time", "time")
-	instantiate_attribute(new_runtime_model, time, "start_time", current_time)
-	instantiate_attribute(new_runtime_model, time, "current_time", current_time)
-
-	return new_runtime_model!
-
-Element function create_schedule(model : Element):
-	// Create nice graph first
-	Element nodes
-	Element successors
-	String element_name
-	Element incoming_links
-	Element all_blocks
-
-	nodes = allInstances(model, "Block")
-	successors = create_node()
-	while (read_nr_out(nodes) > 0):
-		element_name = set_pop(nodes)
-		if (bool_not(dict_in(successors, element_name))):
-			dict_add(successors, element_name, create_node())
-
-		if (is_nominal_instance(model, element_name, "ICBlock")):
-			if (element_eq(read_attribute(model, element_name, "last_in"), read_root())):
-				incoming_links = allIncomingAssociationInstances(model, element_name, "InitialCondition")
-			else:
-				incoming_links = create_node()
-			if (is_nominal_instance(model, element_name, "DerivatorBlock")):
-				Element new_incoming_links
-				new_incoming_links = allIncomingAssociationInstances(model, element_name, "Link")
-				while (read_nr_out(new_incoming_links) > 0):
-					list_append(incoming_links, set_pop(new_incoming_links))
-		else:
-			incoming_links = allIncomingAssociationInstances(model, element_name, "Link")
-
-		while (read_nr_out(incoming_links) > 0):
-			String source
-			source = readAssociationSource(model, set_pop(incoming_links))
-			if (bool_not(dict_in(successors, source))):
-				dict_add(successors, source, create_node())
-			set_add(successors[source], element_name)
-	
-	Element values
-	values = create_node()
-	dict_add(values, "S", create_node())
-	dict_add(values, "index", 0)
-	dict_add(values, "indices", create_node())
-	dict_add(values, "lowlink", create_node())
-	dict_add(values, "onStack", create_node())
-	dict_add(values, "successors", successors)
-	dict_add(values, "SCC", create_node())
-
-	nodes = allInstances(model, "Block")
-	while (read_nr_out(nodes) > 0):
-		strongconnect(set_pop(nodes), values)
-
-	return values["SCC"]!
-
-Integer function min(a : Integer, b : Integer):
-	if (a < b):
-		return a!
-	else:
-		return b!
-
-Void function strongconnect(v : String, values : Element):
-	if (dict_in(values["indices"], v)):
-		return!
-
-	dict_overwrite(values["indices"], v, values["index"])
-	dict_overwrite(values["lowlink"], v, values["index"])
-	dict_overwrite(values, "index", cast_s2i(cast_v2s(values["index"])) + 1)
-
-	list_append(values["S"], v)
-	dict_overwrite(values["onStack"], v, True)
-	
-	Element successors
-	String w
-	successors = values["successors"][v]
-	while (read_nr_out(successors) > 0):
-		w = set_pop(successors)
-		if (bool_not(dict_in(values["indices"], w))):
-			strongconnect(w, values)
-			dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["lowlink"][w]))
-		elif (dict_in(values["onStack"], w)):
-			if (values["onStack"][w]):
-				dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["indices"][w]))
-	
-	if (value_eq(values["lowlink"][v], values["indices"][v])):
-		Element scc
-		scc = create_node()
-		// It will always differ now
-		w = list_pop(values["S"])
-		list_append(scc, w)
-		dict_overwrite(values["onStack"], w, False)
-		while (w != v):
-			w = list_pop(values["S"])
-			list_append(scc, w)
-			dict_overwrite(values["onStack"], w, False)
-		list_insert(values["SCC"], scc, 0)
-
-	return!
-
-Element function list_pop(list : Element):
-	Integer top
-	Element t
-	top = list_len(list) - 1
-	t = list_read(list, top)
-	list_delete(list, top)
-	return t!
-
-String function readType(model : Element, name : String):
-	return reverseKeyLookup(model["metamodel"]["model"], dict_read_node(model["type_mapping"], model["model"][name]))!
-
-Boolean function solve_scc(model : Element, scc : Element):
-	Element m
-	Integer i
-	Integer j
-	String block
-	String blocktype
-	Element incoming
-	String selected
-	Float constant
-	Element t
-
-	// Construct the matrix first, with as many rows as there are variables
-	// Number of columns is 1 higher
-	i = 0
-	m = create_node()
-	while (i < read_nr_out(scc)):
-		j = 0
-		t = create_node()
-		while (j < (read_nr_out(scc) + 1)):
-			list_append(t, 0.0)
-			j = j + 1
-		list_append(m, t)
-		i = i + 1
-
-	log("Matrix ready!")
-	// Matrix initialized to 0.0
-	i = 0
-	while (i < read_nr_out(scc)):
-		log("Creating matrix row")
-		// First element of scc
-		block = scc[i]
-		blocktype = readType(model, block)
-
-		// First write 1 in the current block
-		dict_overwrite(m[i], i, 1.0)
-
-		// Now check all blocks that are incoming
-		if (blocktype == "AdditionBlock"):
-			constant = 0.0
-		elif (blocktype == "MultiplyBlock"):
-			constant = 1.0
-
-		log("Generating matrix for " + blocktype)
-		log("Block: " + block)
-		incoming = allIncomingAssociationInstances(model, block, "Link")
-
-		Integer index_to_write_constant
-		index_to_write_constant = -1
-		log("Iterating over incoming")
-		while (read_nr_out(incoming) > 0):
-			log("Iteration")
-			selected = readAssociationSource(model, set_pop(incoming))
-
-			if (set_in(scc, selected)):
-				// Part of the loop, so in the index of selected in scc
-				// Five options:
-				if (blocktype == "AdditionBlock"):
-					// 1) AdditionBlock
-					// Add the negative of this signal, which is as of yet unknown
-					// x = y + z --> x - y - z = 0
-					dict_overwrite(m[i], list_index_of(scc, selected), -1.0)
-				elif (blocktype == "MultiplyBlock"):
-					// 2) MultiplyBlock
-					if (index_to_write_constant != -1):
-						return False!
-					index_to_write_constant = list_index_of(scc, selected)
-				elif (blocktype == "NegatorBlock"):
-					// 3) NegatorBlock
-					// Add the positive of the signal, which is as of yet unknown
-					dict_overwrite(m[i], list_index_of(scc, selected), 1.0)
-				elif (blocktype == "DelayBlock"):
-					// 5) DelayBlock
-					// Just copies a single value
-					dict_overwrite(m[i], list_index_of(scc, selected), -1.0)
-				else:
-					// Block that cannot be handled
-					return False!
-			else:
-				// A constant, which we can assume is already computed and thus usable
-				if (blocktype == "AdditionBlock"):
-					constant = constant + v2f(read_attribute(model, selected, "signal"))
-					dict_overwrite(m[i], read_nr_out(scc), constant)
-				elif (blocktype == "MultiplyBlock"):
-					constant = constant * v2f(read_attribute(model, selected, "signal"))
-					// Not written to constant part, as multiplies a variable
-
-				// Any other block is impossible:
-				// * Constant would never be part of a SCC
-				// * Delay would never get an incoming constant
-				// * Negation and Inverse only get 1 input, which is a variable in a loop
-				// * Integrator and Derivator never get an incoming constant
-
-		if (index_to_write_constant != -1):
-			dict_overwrite(m[i], index_to_write_constant, -constant)
-
-		i = i + 1
-
-	// Constructed a complete matrix, so we can start!
-	log("Constructed matrix to solve:")
-	log(matrix2string(m))
-
-	// Solve matrix now
-	eliminateGaussJordan(m)
-
-	// Now go over m and set signals for each element
-	// Assume that everything worked out...
-	i = 0
-	while (i < read_nr_out(m)):
-		block = scc[i]
-		unset_attribute(model, block, "signal")
-		instantiate_attribute(model, block, "signal", m[i][read_nr_out(scc)])
-		log((("Solved " + block) + " to ") + cast_v2s(m[i][read_nr_out(scc)]))
-		i = i + 1
-
-	return True!
-
-Integer function list_index_of(lst : Element, elem : Element):
-	Integer i
-	i = 0
-	while (i < read_nr_out(lst)):
-		if (value_eq(list_read(lst, i), elem)):
-			return i!
-		else:
-			i = i + 1
-	return -1!
-
-Void function step_simulation(model : Element, schedule : Element):
-	String time
-	Float signal
-	Element incoming
-	String selected
-	String block
-	String elem
-	String blocktype
-	Element memory_blocks
-	Integer i
-	Float delta_t
-	Element scc
-
-	time = "time"
-	delta_t = 0.1
-
-	memory_blocks = create_node()
-	output("SIM_TIME " + cast_v2s(read_attribute(model, time, "current_time")))
-	i = 0
-	while (i < read_nr_out(schedule)):
-		scc = list_read(schedule, i)
-		i = i + 1
-
-		if (list_len(scc) > 1):
-			log("Solving algebraic loop!")
-			if (bool_not(solve_scc(model, scc))):
-				output("ALGEBRAIC_LOOP")
-				return !
-		else:
-			block = set_pop(scc)
-
-			// Execute "block"
-			blocktype = readType(model, block)
-			if (blocktype == "ConstantBlock"):
-				signal = read_attribute(model, block, "value")
-			elif (blocktype == "AdditionBlock"):
-				signal = 0.0
-				incoming = allIncomingAssociationInstances(model, block, "Link")
-				while (read_nr_out(incoming) > 0):
-					selected = readAssociationSource(model, set_pop(incoming))
-					signal = signal + cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
-			elif (blocktype == "MultiplyBlock"):
-				signal = 1.0
-				incoming = allIncomingAssociationInstances(model, block, "Link")
-				while (read_nr_out(incoming) > 0):
-					selected = readAssociationSource(model, set_pop(incoming))
-					signal = signal * cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
-			elif (blocktype == "NegatorBlock"):
-				incoming = allIncomingAssociationInstances(model, block, "Link")
-				signal = 0.0
-				while (read_nr_out(incoming) > 0):
-					selected = readAssociationSource(model, set_pop(incoming))
-					signal = float_neg(cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
-			elif (blocktype == "InverseBlock"):
-				signal = 0.0
-				incoming = allIncomingAssociationInstances(model, block, "Link")
-				while (read_nr_out(incoming) > 0):
-					selected = readAssociationSource(model, set_pop(incoming))
-					signal = float_division(1.0, cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
-			elif (blocktype == "DelayBlock"):
-				signal = 0.0
-				if (element_eq(read_attribute(model, block, "last_in"), read_root())):
-					// No memory yet, so use initial condition
-					incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
-					while (read_nr_out(incoming) > 0):
-						selected = readAssociationSource(model, set_pop(incoming))
-						signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
-				else:
-					signal = read_attribute(model, block, "last_in")
-					unset_attribute(model, block, "last_in")
-				set_add(memory_blocks, block)
-			elif (blocktype == "IntegratorBlock"):
-				if (element_eq(read_attribute(model, block, "last_in"), read_root())):
-					// No history yet, so use initial values
-					incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
-					while (read_nr_out(incoming) > 0):
-						selected = readAssociationSource(model, set_pop(incoming))
-						signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
-				else:
-					signal = cast_s2f(cast_v2s(read_attribute(model, block, "last_in"))) + (delta_t * cast_s2f(cast_v2s(read_attribute(model, block, "last_out"))))
-					unset_attribute(model, block, "last_in")
-					unset_attribute(model, block, "last_out")
-				instantiate_attribute(model, block, "last_out", signal)
-				set_add(memory_blocks, block)
-			elif (blocktype == "DerivatorBlock"):
-				if (element_eq(read_attribute(model, block, "last_in"), read_root())):
-					// No history yet, so use initial values
-					incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
-					while (read_nr_out(incoming) > 0):
-						selected = readAssociationSource(model, set_pop(incoming))
-						signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
-				else:
-					incoming = allIncomingAssociationInstances(model, block, "Link")
-					while (read_nr_out(incoming) > 0):
-						selected = readAssociationSource(model, set_pop(incoming))
-						signal = (cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))) - cast_s2f(cast_v2s(read_attribute(model, block, "last_in")))) / delta_t
-					unset_attribute(model, block, "last_in")
-				set_add(memory_blocks, block)
-			elif (blocktype == "ProbeBlock"):
-				incoming = allIncomingAssociationInstances(model, block, "Link")
-				while (read_nr_out(incoming) > 0):
-					selected = readAssociationSource(model, set_pop(incoming))
-					signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
-					output((("SIM_PROBE " + cast_v2s(read_attribute(model, block, "name"))) + " ") + cast_v2s(signal))
-
-			unset_attribute(model, block, "signal")
-			instantiate_attribute(model, block, "signal", signal)
-	output("SIM_END")
-	
-	while (read_nr_out(memory_blocks) > 0):
-		block = set_pop(memory_blocks)
-		// Update memory
-		incoming = allIncomingAssociationInstances(model, block, "Link")
-		while (read_nr_out(incoming) > 0):
-			selected = readAssociationSource(model, set_pop(incoming))
-			instantiate_attribute(model, block, "last_in", cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
-
-	// Increase simulation time
-	Float new_time
-	new_time = cast_s2f(cast_v2s(read_attribute(model, time, "current_time"))) + delta_t
-	unset_attribute(model, time, "current_time")
-	instantiate_attribute(model, time, "current_time", new_time)
-
-	return !
-
-Void function execute_cbd(design_model : Element):
-	String verify_result
-	Element runtime_model
-	Element old_runtime_model
-	String cmd
-	Boolean running
-	Element schedule_init
-	Element schedule_run
-	Element schedule
-	String conforming
-
-	old_runtime_model = instantiate_model(import_node("models/CausalBlockDiagrams_Runtime"))
-	runtime_model = retype_to_runtime(design_model)
-	runtime_model = sanitize(runtime_model, old_runtime_model)
-	running = False
-	conforming = conformance_scd(design_model)
-	if (conforming == "OK"):
-		output("CONFORMANCE_OK")
-	else:
-		output("CONFORMANCE_FAIL")
-
-	schedule_init = create_schedule(runtime_model)
-	schedule_run = read_root()
-
-	while (True):
-		// If we are running, we just don't block for input and automatically do a step if there is no input
-		if (running):
-			if (has_input()):
-				cmd = input()
-			else:
-				cmd = "step"
-		else:
-			cmd = input()
-
-		// Process input
-		if (cmd == "simulate"):
-			// Simulation should toggle running to True, but only if the model is conforming
-			if (conforming == "OK"):
-				running = True
-			else:
-				output("CONFORMANCE_FAIL " + conforming)
-
-		elif (cmd == "step"):
-			// Stepping should make a single step, but first need to pick the correct schedule to use
-			if (conforming == "OK"):
-				if (read_attribute(runtime_model, "time", "start_time") == read_attribute(runtime_model, "time", "current_time")):
-					schedule = schedule_init
-				else:
-					if (element_eq(schedule_run, read_root())):
-						schedule_run = create_schedule(runtime_model)
-					schedule = schedule_run
-				// TODO remove
-				schedule = create_schedule(runtime_model)
-				step_simulation(runtime_model, schedule)
-			else:
-				output("CONFORMANCE_FAIL " + conforming)
-
-		elif (cmd == "pause"):
-			// Pausing merely stops a running simulation
-			running = False
-
-		elif (cmd == "read_available_attributes"):
-			// Returns a list of all available attributes
-			Element attr_list
-			Element attrs
-			Element attr
-			attr_list = getAttributeList(design_model, input())
-			attrs = dict_keys(attr_list)
-			while (0 < read_nr_out(attrs)):
-				attr = set_pop(attrs)
-				output("AVAILABLE_ATTR_VALUE " + cast_v2s(attr))
-				output("AVAILABLE_ATTR_TYPE " + cast_v2s(dict_read(attr_list, attr)))
-			output("AVAILABLE_ATTR_END")
-
-		elif (cmd == "read_attribute"):
-			// Returns the value of an attribute
-			output("ATTR_VALUE " + cast_v2s(read_attribute(design_model, input(), input())))
-
-		elif (bool_or(bool_or(cmd == "set_attribute", cmd == "instantiate_node"), bool_or(cmd == "delete_element", cmd == "instantiate_association"))):
-			// Modify the structure
-			if (cmd == "set_attribute"):
-				// Setting an attribute
-				String element_name
-				String attribute_name
-				element_name = input()
-				attribute_name = input()
-
-				// Delete it if it exists already
-				if (bool_not(element_eq(read_attribute(design_model, element_name, attribute_name), read_root()))):
-					unset_attribute(design_model, element_name, attribute_name)
-
-				// And finally set it
-				instantiate_attribute(design_model, element_name, attribute_name, input())
-
-			elif (cmd == "instantiate_node"):
-				// Instantiate a node
-				instantiate_node(design_model, input(), input())
-
-			elif (cmd == "instantiate_association"):
-				// Instantiate an association
-				instantiate_link(design_model, input(), input(), input(), input())
-
-			elif (cmd == "delete_element"):
-				// Delete the provided element
-				model_delete_element(design_model, input())
-
-			// After changes, we check whether or not the design model conforms
-			conforming = conformance_scd(design_model)
-			if (conforming == "OK"):
-				// Conforming, so do the retyping and sanitization step
-				runtime_model = retype_to_runtime(design_model)
-				runtime_model = sanitize(runtime_model, old_runtime_model)
-				schedule_init = create_schedule(runtime_model)
-				schedule_run = read_root()
-				old_runtime_model = runtime_model
-				output("CONFORMANCE_OK")
-			else:
-				// Not conforming, so stop simulation and block for input (preferably a modify to make everything consistent again)
-				running = False
-				output("CONFORMANCE_FAIL " + conforming)
-		else:
-			log("Did not understand command: " + cmd)
-
-Float function v2f(i : Element):
-	return cast_s2f(cast_v2s(i))!
-
-Void function eliminateGaussJordan(m : Element):
-	Integer i
-	Integer j
-	Integer f
-	Integer g
-	Boolean searching
-	Element t
-	Float divisor
-
-	i = 0
-	j = 0
-
-	while (i < read_nr_out(m)):
-		// Make sure pivot m[i][j] != 0, swapping if necessary
-		while (v2f(m[i][j]) == 0.0):
-			// Is zero, so find row which is not zero
-			f = i + 1
-			searching = True
-			while (searching):
-				if (f >= read_nr_out(m)):
-					// No longer any rows left, so just increase column counter
-					searching = False
-					j = j + 1
-				else:
-					if (v2f(m[f][j]) == 0.0):
-						// Also zero, so continue
-						f = f + 1
-					else:
-						// Found non-zero, so swap row
-						t = v2f(m[f])
-						dict_overwrite(m, f, v2f(m[i]))
-						dict_overwrite(m, i, t)
-						searching = False
-			// If we have increased j, we will just start the loop again (possibly), as m[i][j] might be zero again
-
-		// Pivot in m[i][j] guaranteed to not be 0
-		// Now divide complete row by value of m[i][j] to make it equal 1
-		f = j
-		divisor = v2f(m[i][j])
-		while (f < read_nr_out(m[i])):
-			dict_overwrite(m[i], f, float_division(v2f(m[i][f]), divisor))
-			f = f + 1
-
-		// Eliminate all rows in the j-th column, except the i-th row
-		f = 0
-		while (f < read_nr_out(m)):
-			if (bool_not(f == i)):
-				g = j
-				divisor = v2f(m[f][j])
-				while (g < read_nr_out(m[f])):
-					dict_overwrite(m[f], g, v2f(m[f][g]) - (divisor * v2f(m[i][g])))
-					g = g + 1
-			f = f + 1
-
-		// Increase row and column
-		i = i + 1
-		j = j + 1
-
-	return !
-
-String function matrix2string(m : Element):
-	Integer i
-	Integer j
-	String result
-
-	result = ""
-	i = 0
-	while (i < read_nr_out(m)):
-		j = 0
-		while (j < read_nr_out(m[i])):
-			result = result + cast_v2s(m[i][j])
-			result = result + ", "
-			j = j + 1
-		i = i + 1
-		result = result + "\n"
-	return result!
-
-Void function main():
-	Element model
-	String verify_result
-
-	while (True):
-		execute_cbd(instantiate_model(import_node("models/CausalBlockDiagrams_Design")))
-
-	return!

+ 0 - 32
integration/code/fsa_design.mvc

@@ -1,32 +0,0 @@
-import models/SimpleClassDiagrams as SCD
-include "primitives.alh"
-
-SCD FiniteStateAutomata_Design{
-    AttributeValue String {
-        constraint = $
-            String constraint(model : Element, name : String):
-                if (bool_not(is_physical_string(model["model"][name]))):
-                    return "String has no string value"!
-                else:
-                    return "OK"!
-            $
-    }
-
-    Class State {
-        name : String
-    }
-
-    Class InitialState {
-        lower_cardinality = 1
-        upper_cardinality = 1
-    }
-
-    Association Transition (State, State) {
-        event : String
-        raise? : String
-    }
-
-    Inheritance (InitialState, State){}
-}
-
-export FiniteStateAutomata_Design to models/FiniteStateAutomata_Design

+ 0 - 42
integration/code/fsa_runtime.mvc

@@ -1,42 +0,0 @@
-import models/SimpleClassDiagrams as SCD
-include "primitives.alh"
-
-SCD FiniteStateAutomata_Runtime{
-    AttributeValue String {
-        constraint = $
-            String constraint(model : Element, name : String):
-                if (bool_not(is_physical_string(model["model"][name]))):
-                    return "String has no string value"!
-                else:
-                    return "OK"!
-            $
-    }
-
-    Class State {
-        name : String
-    }
-
-    Class InitialState {
-        lower_cardinality = 1
-        upper_cardinality = 1
-    }
-
-    Association Transition (State, State){
-        event : String
-        raise? : String
-    }
-
-    Inheritance (InitialState, State){}
-
-    Class CurrentState{
-        lower_cardinality = 1
-        upper_cardinality = 1
-    }
-
-    Association CurrentStateLink{
-        lower_cardinality = 1
-        upper_cardinality = 1
-    }
-}
-
-export FiniteStateAutomata_Runtime to models/FiniteStateAutomata_Runtime

+ 0 - 256
integration/code/fsa_semantics.alc

@@ -1,256 +0,0 @@
-include "primitives.alh"
-include "modelling.alh"
-include "object_operations.alh"
-include "library.alh"
-include "conformance_scd.alh"
-include "io.alh"
-include "metamodels.alh"
-include "compilation_manager.alh"
-
-Element function retype_to_runtime(design_model : Element):
-	Element runtime_model
-	Element all_states
-	Element all_links
-	String mm_type_name
-	String element_name
-	String attr_name
-	String attr_value
-	String attribute
-	String src
-	String dst
-	String time
-
-	runtime_model = instantiate_model(import_node("models/FiniteStateAutomata_Runtime"))
-
-	log("Retyping")
-	all_states = allInstances(design_model, "State")
-	while (list_len(all_states) > 0):
-		element_name = set_pop(all_states)
-		mm_type_name = reverseKeyLookup(design_model["metamodel"]["model"], dict_read_node(design_model["type_mapping"], design_model["model"][element_name]))
-		element_name = instantiate_node(runtime_model, mm_type_name, element_name)
-		instantiate_attribute(runtime_model, element_name, "name", read_attribute(design_model, element_name, "name"))
-
-	// Don't merge this together with the block conversion, as the destination block might not exist yet!
-	all_links = allInstances(design_model, "Transition")
-	while (read_nr_out(all_links) > 0):
-		element_name = set_pop(all_links)
-		src = reverseKeyLookup(design_model["model"], read_edge_src(design_model["model"][element_name]))
-		dst = reverseKeyLookup(design_model["model"], read_edge_dst(design_model["model"][element_name]))
-		instantiate_link(runtime_model, "Transition", element_name, src, dst)
-		instantiate_attribute(runtime_model, element_name, "event", read_attribute(design_model, element_name, "event"))
-
-		if (element_neq(read_attribute(design_model, element_name, "raise"), read_root())):
-			// There is a raise attribute
-			instantiate_attribute(runtime_model, element_name, "raise", read_attribute(design_model, element_name, "raise"))
-
-	log("DONE")
-	return runtime_model!
-
-Element function sanitize(new_runtime_model : Element, old_runtime_model : Element, auto : Boolean):
-	String cstate
-	String cstate_obj
-	log("Start sanitize")
-
-	cstate_obj = instantiate_node(new_runtime_model, "CurrentState", "")
-
-	if (read_nr_out(allInstances(old_runtime_model, "CurrentStateLink")) > 0):
-		cstate = readAssociationDestination(old_runtime_model, set_pop(allInstances(old_runtime_model, "CurrentStateLink")))
-		if (bool_not(dict_in(new_runtime_model["model"], cstate))):
-			// Current state removed, so fix
-			log("Removed current state")
-			if (auto):
-				log("Auto-fixing the problem")
-				cstate = set_pop(allInstances(new_runtime_model, "InitialState"))
-			else:
-				log("Please give new state")
-				while (bool_not(dict_in(new_runtime_model["model"], cstate))):
-					output("REQUEST_CURRENT_STATE")
-					cstate = input()
-	else:
-		// Initialize for the first time
-		cstate = set_pop(allInstances(new_runtime_model, "InitialState"))
-	
-	instantiate_link(new_runtime_model, "CurrentStateLink", "", cstate_obj, cstate)
-
-	log("Sanitize OK")
-	return new_runtime_model!
-
-Void function do_transition(model : Element, start_time : Float, event : String):
-	// Read out current state
-	String cstate_link
-	String cstate_obj
-	String cstate
-	String transition
-	String new_state
-	String raise
-
-	log("Transition executing")
-	cstate_link = set_pop(allInstances(model, "CurrentStateLink"))
-	cstate = readAssociationDestination(model, cstate_link)
-	cstate_obj = readAssociationSource(model, cstate_link)
-
-	// Read out all outgoing transitions
-	Element all_transitions
-	all_transitions = allOutgoingAssociationInstances(model, cstate, "Transition")
-
-	output("SIM_TIME " + cast_v2s(time() - start_time))
-	output("SIM_EVENT " + cast_v2s(event))
-
-	while (read_nr_out(all_transitions) > 0):
-		transition = set_pop(all_transitions)
-		if (value_eq(read_attribute(model, transition, "event"), event)):
-			// Found a match
-			new_state = readAssociationDestination(model, transition)
-			log("Transition to " + new_state)
-
-			// Delete current state
-			model_delete_element(model, cstate_link)
-
-			// Set destination of state
-			instantiate_link(model, "CurrentStateLink", "", cstate_obj, new_state)
-
-			log("Do state change")
-			output("SIM_STATE " + cast_v2s(read_attribute(model, new_state, "name")))
-
-			// Raise "raise" attribute of transition
-			raise = read_attribute(model, transition, "raise")
-			if (element_neq(raise, read_root())):
-				// Raise the event
-				output("SIM_RAISE " + cast_v2s(raise))
-
-			return !
-
-	return!
-
-Void function execute_fsa(design_model : Element):
-	String verify_result
-	Element runtime_model
-	Element old_runtime_model
-	String cmd
-	Boolean running
-	String conforming
-	Float simulation_time
-	Float start_time
-	Boolean automatic_sanitization
-
-	automatic_sanitization = True
-	start_time = time()
-	simulation_time = 0.0
-	old_runtime_model = instantiate_model(import_node("models/FiniteStateAutomata_Runtime"))
-	runtime_model = retype_to_runtime(design_model)
-
-	conforming = conformance_scd(design_model)
-	log("Conformance: " + conforming)
-	if (conforming == "OK"):
-		output("CONFORMANCE_OK")
-	else:
-		output("CONFORMANCE_FAIL")
-
-	while (True):
-		cmd = input()
-		log("Do: " + cmd)
-
-		if (cmd == "pause"):
-			// Pausing merely stops a running simulation
-			if (running):
-				simulation_time = time() - start_time
-				running = False
-				output("PAUSED")
-
-		elif (cmd == "simulate"):
-			// Continue simulation, so reset the value
-			if (bool_not(running)):
-				start_time = time() - simulation_time
-				running = True
-				output("CONTINUE")
-			
-		elif (cmd == "auto_sanitize"):
-			automatic_sanitization = input()
-
-		elif (cmd == "event"):
-			log("Got event")
-			do_transition(runtime_model, start_time, input())
-
-		elif (cmd == "read_available_attributes"):
-			// Returns a list of all available attributes
-			Element attr_list
-			Element attrs
-			Element attr
-			attr_list = getAttributeList(design_model, input())
-			attrs = dict_keys(attr_list)
-			while (0 < read_nr_out(attrs)):
-				attr = set_pop(attrs)
-				output("AVAILABLE_ATTR_VALUE " + cast_v2s(attr))
-				output("AVAILABLE_ATTR_TYPE " + cast_v2s(dict_read(attr_list, attr)))
-			output("AVAILABLE_ATTR_END")
-
-		elif (cmd == "read_attribute"):
-			// Returns the value of an attribute
-			output("ATTR_VALUE " + cast_v2s(read_attribute(design_model, input(), input())))
-
-		elif (bool_or(cmd == "switch_initial", bool_or(bool_or(cmd == "set_attribute", cmd == "instantiate_node"), bool_or(cmd == "delete_element", cmd == "instantiate_association")))):
-			// Modify the structure
-			if (cmd == "set_attribute"):
-				// Setting an attribute
-				String element_name
-				String attribute_name
-				element_name = input()
-				attribute_name = input()
-
-				// Delete it if it exists already
-				if (bool_not(element_eq(read_attribute(design_model, element_name, attribute_name), read_root()))):
-					unset_attribute(design_model, element_name, attribute_name)
-
-				// And finally set it
-				instantiate_attribute(design_model, element_name, attribute_name, input())
-
-			elif (cmd == "instantiate_node"):
-				// Instantiate a node
-				instantiate_node(design_model, input(), input())
-
-			elif (cmd == "instantiate_association"):
-				// Instantiate an association
-				instantiate_link(design_model, input(), input(), input(), input())
-
-			elif (cmd == "delete_element"):
-				// Delete the provided element
-				model_delete_element(design_model, input())
-
-			elif (cmd == "switch_initial"):
-				// Switch the initial state
-				if (read_nr_out(allInstances(design_model, "InitialState")) > 0):
-					retype(design_model, set_pop(allInstances(design_model, "InitialState")), "State")
-
-				retype(design_model, input(), "InitialState")
-
-			// After changes, we check whether or not the design model conforms
-			if (conforming == "OK"):
-				// Was correct, so store just to make sure
-				simulation_time = time() - start_time
-			conforming = conformance_scd(design_model)
-			if (conforming == "OK"):
-				// Conforming, so do the retyping and sanitization step
-				runtime_model = retype_to_runtime(design_model)
-				runtime_model = sanitize(runtime_model, old_runtime_model, automatic_sanitization)
-				old_runtime_model = runtime_model
-				start_time = time() - simulation_time
-				output("CONFORMANCE_OK")
-				log("Conformance became OK")
-			else:
-				// Not conforming, so stop simulation and block for input (preferably a modify to make everything consistent again)
-				output("CONFORMANCE_FAIL " + conforming)
-		else:
-			log("Did not understand command: " + cmd)
-
-		if (bool_and(conforming == "OK", running)):
-			output("SIM_TIME " + cast_v2s(time() - start_time))
-			output("SIM_STATE " + cast_v2s(read_attribute(runtime_model, readAssociationDestination(runtime_model, set_pop(allInstances(runtime_model, "CurrentStateLink"))), "name")))
-
-Void function main():
-	Element model
-	String verify_result
-
-	while (True):
-		execute_fsa(instantiate_model(import_node("models/FiniteStateAutomata_Design")))
-
-	return!

+ 0 - 12
integration/code/ftg.mvc

@@ -1,12 +0,0 @@
-import models/SimpleClassDiagrams as SimpleClassDiagrams
-
-SimpleClassDiagrams FormalismTransformationGraph{
-    Class Formalism {
-        location : String
-    }
-    Association Transformation (Formalism, Formalism) {
-        location : String
-    }
-}
-
-export FormalismTransformationGraph to models/FTG

+ 0 - 8
integration/code/graph.mvc

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

+ 3 - 5
integration/code/initialize_PN.mvc

@@ -1,6 +1,4 @@
-PetriNets_RAM initialize_PN {
-    Composite schedule {
-        {Contains} Success success {}
-    }
-    Initial (schedule, success) {}
+Composite schedule {
+    {Contains} Success success {}
 }
+Initial (schedule, success) {}

+ 13 - 15
integration/code/my_cbd.mvc

@@ -1,16 +1,14 @@
-CBD my_CBD {
-    AdditionBlock c {}
-    ConstantBlock a {
-        value = 1.0
-    }
-    ConstantBlock b {
-        value = 2.0
-    }
-    ProbeBlock d {
-        name = "result"
-    }
-
-    Link (a, c) {}
-    Link (b, c) {}
-    Link (c, d) {}
+AdditionBlock c {}
+ConstantBlock a {
+    value = 1.0
+}
+ConstantBlock b {
+    value = 2.0
 }
+ProbeBlock d {
+    name = "result"
+}
+
+Link (a, c) {}
+Link (b, c) {}
+Link (c, d) {}

+ 0 - 19
integration/code/my_petrinet.mvc

@@ -1,19 +0,0 @@
-import models/PetriNets as PetriNets
-
-PetriNets my_petrinet {
-    Place p1 {
-        tokens = 1
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T (p1, t1) {
-        weight = 1
-    }
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-export my_petrinet to models/my_petrinet

+ 0 - 33
integration/code/my_petrinet_with_MM.mvc

@@ -1,33 +0,0 @@
-import models/SimpleClassDiagrams as SCD
-
-SCD PetriNets{
-    AttributeValue Natural {}
-    Class Place{
-        tokens : Natural
-    }
-    Class Transition{}
-    Association P2T (Place, Transition) {
-        weight : Natural
-    }
-    Association T2P (Transition, Place) {
-        weight : Natural
-    }
-}
-
-PetriNets my_petrinet {
-    Place p1 {
-        tokens = 1
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T (p1, t1) {
-        weight = 1
-    }
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-export my_petrinet to models/my_petrinet

+ 0 - 48
integration/code/my_petrinet_with_MM_and_constraints.mvc

@@ -1,48 +0,0 @@
-import models/SimpleClassDiagrams as SCD
-include "primitives.alh"
-
-SCD PetriNets{
-    SimpleAttribute Natural {
-        constraint =
-            $
-            String function constraint_Natural(model : Element, name : String):
-                Element self
-                self = model["model"][name]
-                if (is_physical_int(self)):
-                    if (integer_gte(self, 0)):
-                        return "OK"!
-                    else:
-                        return "Natural number not larger than or equal to zero"!
-                else:
-                    return "Natural number not larger than or equal to zero"!
-            $
-    }
-    Class Place{
-        tokens : Natural
-    }
-    Class Transition{}
-    Association P2T (Place, Transition) {
-        weight : Natural
-    }
-    Association T2P (Transition, Place) {
-        weight : Natural
-    }
-}
-
-PetriNets my_petrinet {
-    Place p1 {
-        tokens = 1
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T (p1, t1) {
-        weight = 1
-    }
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-export my_petrinet to models/my_petrinet

+ 10 - 16
integration/code/petrinets.mvc

@@ -1,18 +1,12 @@
-import models/SimpleClassDiagrams as SimpleClassDiagrams
+SimpleAttribute Natural {}
 
-SimpleClassDiagrams PetriNets{
-    SimpleAttribute Natural {}
-
-    Class Place{
-        tokens : Natural
-    }
-    Class Transition{}
-    Association P2T (Place, Transition) {
-        weight : Natural
-    }
-    Association T2P (Transition, Place) {
-        weight : Natural
-    }
+Class Place{
+    tokens : Natural
+}
+Class Transition{}
+Association P2T (Place, Transition) {
+    weight : Natural
+}
+Association T2P (Transition, Place) {
+    weight : Natural
 }
-
-export PetriNets to models/PetriNets

+ 0 - 36
integration/code/petrinets_constraints.mvc

@@ -1,36 +0,0 @@
-import models/SimpleClassDiagrams as SCD
-include "primitives.alh"
-
-SCD PetriNets{
-    SimpleAttribute Natural {
-        constraint =
-            $
-            String function constraint_Natural(model : Element, name : String):
-                Element self
-                self = model["model"][name]
-                if (is_physical_int(self)):
-                    if (integer_gte(self, 0)):
-                        return "OK"!
-                    else:
-                        return "Natural number not larger than or equal to zero"!
-                else:
-                    return "Natural number not larger than or equal to zero"!
-            $
-    }
-
-    Class Place{
-        tokens : Natural
-    }
-
-    Class Transition{}
-
-    Association P2T (Place, Transition) {
-        weight : Natural
-    }
-
-    Association T2P (Transition, Place) {
-        weight : Natural
-    }
-}
-
-export PetriNets to models/PetriNets

+ 36 - 38
integration/code/pm_pn_reachability.mvc

@@ -1,41 +1,39 @@
-ProcessModel combo_reach {
-    Start start {}
-    Finish finish {}
-    Exec initializePN {
-        name = "initialize_PN"
-    }
-    Exec refinePN {
-        name = "refine_PN"
-    }
-    Exec reachability {
-        name = "reachability"
-    }
-    Exec reachability_print{
-        name = "reachability_print"
-    }
-    
-    Data pn {
-        name = "pn"
-        type = "PetriNet"
-    }
-    Data reachability_graph {
-        name = "reachability"
-        type = "ReachabilityGraph"
-    }
+Start start {}
+Finish finish {}
+Exec initializePN {
+    name = "initialize_PN"
+}
+Exec refinePN {
+    name = "refine_PN"
+}
+Exec reachability {
+    name = "reachability"
+}
+Exec reachability_print{
+    name = "reachability_print"
+}
 
-    Next (start, initializePN) {}
-    Next (initializePN, refinePN) {}
-    Next (refinePN, reachability) {}
-    Next (reachability, reachability_print) {}
-    Next (reachability_print, finish) {}
+Data pn {
+    name = "pn"
+    type = "PetriNet"
+}
+Data reachability_graph {
+    name = "reachability"
+    type = "ReachabilityGraph"
+}
+
+Next (start, initializePN) {}
+Next (initializePN, refinePN) {}
+Next (refinePN, reachability) {}
+Next (reachability, reachability_print) {}
+Next (reachability_print, finish) {}
 
-    Produces (initializePN, pn) {}
-    Consumes (refinePN, pn) {
-    }
-    Produces (refinePN, pn) {}
-    Consumes (reachability, pn) {
-    }
-    Produces (reachability, reachability_graph) {}
-    Consumes (reachability_print, reachability_graph) {
-    }
+Produces (initializePN, pn) {}
+Consumes (refinePN, pn) {
+}
+Produces (refinePN, pn) {}
+Consumes (reachability, pn) {
+}
+Produces (reachability, reachability_graph) {}
+Consumes (reachability_print, reachability_graph) {
 }

+ 0 - 16
integration/code/pn_critical_section.mvc

@@ -1,16 +0,0 @@
-PetriNets critical_section{
-    Place crit_1{
-        name = "CS1"
-        tokens = 0
-    }
-
-    Place crit_2{
-        name = "CS2"
-        tokens = 0
-    }
-
-    Place available{
-        name = "available"
-        tokens = 1
-    }
-}

+ 14 - 20
integration/code/pn_design.mvc

@@ -1,22 +1,16 @@
-import models/SimpleClassDiagrams as SimpleClassDiagrams
+SimpleAttribute Natural {}
+SimpleAttribute String {}
 
-SimpleClassDiagrams PetriNets_Design{
-    SimpleAttribute Natural {}
-    SimpleAttribute String {}
-
-    Class Place {
-        tokens : Natural
-        name : String
-    }
-    Class Transition {
-        name : String
-    }
-    Association P2T (Place, Transition) {
-        weight : Natural
-    }
-    Association T2P (Transition, Place) {
-        weight : Natural
-    }
+Class Place {
+    tokens : Natural
+    name : String
+}
+Class Transition {
+    name : String
+}
+Association P2T (Place, Transition) {
+    weight : Natural
+}
+Association T2P (Transition, Place) {
+    weight : Natural
 }
-
-export PetriNets_Design to models/PetriNets_Design

+ 23 - 29
integration/code/pn_design_model.mvc

@@ -1,30 +1,24 @@
-import models/PetriNets_Design as PetriNets
-
-PetriNets pn {
-    Place p1 {
-        tokens = 1
-        name = "p1"
-    }
-    Place p2 {
-        tokens = 2
-        name = "p2"
-    }
-    Place p3 {
-        tokens = 3
-        name = "p3"
-    }
-    Transition t1 {
-        name = "t1"
-    }
-    P2T (p1, t1) {
-        weight = 1
-    }
-    P2T (p2, t1) {
-        weight = 1
-    }
-    T2P (t1, p3) {
-        weight = 2
-    }
+Place p1 {
+    tokens = 1
+    name = "p1"
+}
+Place p2 {
+    tokens = 2
+    name = "p2"
+}
+Place p3 {
+    tokens = 3
+    name = "p3"
+}
+Transition t1 {
+    name = "t1"
+}
+P2T (p1, t1) {
+    weight = 1
+}
+P2T (p2, t1) {
+    weight = 1
+}
+T2P (t1, p3) {
+    weight = 2
 }
-
-export pn to models/pn

+ 0 - 63
integration/code/pn_design_model_larger.mvc

@@ -1,63 +0,0 @@
-import models/PetriNets_Design as PetriNets
-
-PetriNets pn {
-    Place critical_section_1 {
-        tokens = 0
-        name = "critical_section_1"
-    }
-    Place critical_section_2 {
-        tokens = 0
-        name = "critical_section_2"
-    }
-    Place lock_available {
-        tokens = 1
-        name = "lock_available"
-    }
-
-    Transition release_section_1 {
-        name = "release_section_1"
-    }
-    Transition release_section_2 {
-        name = "release_section_2"
-    }
-    Transition acquire_section_1 {
-        name = "acquire_section_1"
-    }
-    Transition acquire_section_2 {
-        name = "acquire_section_2"
-    }
-
-    P2T (critical_section_1, release_section_1) {
-        weight = 1
-    }
-
-    P2T (critical_section_2, release_section_2) {
-        weight = 1
-    }
-
-    P2T (lock_available, acquire_section_1) {
-        weight = 1
-    }
-
-    P2T (lock_available, acquire_section_2) {
-        weight = 1
-    }
-
-    T2P (release_section_1, lock_available) {
-        weight = 1
-    }
-
-    T2P (release_section_2, lock_available) {
-        weight = 1
-    }
-
-    T2P (acquire_section_1, critical_section_1) {
-        weight = 1
-    }
-
-    T2P (acquire_section_2, critical_section_2) {
-        weight = 1
-    }
-}
-
-export pn to models/pn

+ 165 - 170
integration/code/pn_design_to_runtime.mvc

@@ -1,183 +1,178 @@
-import models/RAM_PetriNet_Design_Runtime as RAM_PN_DR
 include "primitives.alh"
 include "modelling.alh"
 
-RAM_PN_DR annotate {
-    Composite schedule {
-        {Contains} Failure failure {}
-        {Contains} Success success {}
-        {Contains} ForAll copy_transitions {
-            LHS {
-                Pre_PetriNet/Transition {
-                    label = "0"
-                }
-            }
-            RHS {
-                Post_PetriNet/Transition ct1 {
-                    label = "0"
-                }
-                Post_PetriNet_Runtime/Transition ct2 {
-                    label = "1"
-                    value_executing = $
-                        Boolean function value(model : Element, name : String, mapping : Element):
-                            return True!
-                        $
-                    value_name = $
-                        Integer function value(model : Element, name : String, mapping : Element):
-                            return read_attribute(model, mapping["0"], "name")!
-                        $
-                }
-                Post_D2R_TransitionLink (ct1, ct2){
-                    label = "2"
-                }
+Composite schedule {
+    {Contains} Failure failure {}
+    {Contains} Success success {}
+    {Contains} ForAll copy_transitions {
+        LHS {
+            Pre_PetriNet/Transition {
+                label = "0"
             }
         }
-        {Contains} ForAll copy_places {
-            LHS {
-                Pre_PetriNet/Place {
-                    label = "0"
-                }
-            }
-            RHS {
-                Post_PetriNet/Place cp1 {
-                    label = "0"
-                }
-                Post_PetriNet_Runtime/Place cp2 {
-                    label = "1"
-                    value_tokens = $
-                        Integer function value(model : Element, name : String, mapping : Element):
-                            return read_attribute(model, mapping["0"], "tokens")!
-                        $
-                    value_name = $
-                        Integer function value(model : Element, name : String, mapping : Element):
-                            return read_attribute(model, mapping["0"], "name")!
-                        $
-                }
-                Post_D2R_PlaceLink (cp1, cp2){
-                    label = "2"
-                }
+        RHS {
+            Post_PetriNet/Transition ct1 {
+                label = "0"
+            }
+            Post_PetriNet_Runtime/Transition ct2 {
+                label = "1"
+                value_executing = $
+                    Boolean function value(model : Element, name : String, mapping : Element):
+                        return True!
+                    $
+                value_name = $
+                    Integer function value(model : Element, name : String, mapping : Element):
+                        return read_attribute(model, mapping["0"], "name")!
+                    $
+            }
+            Post_D2R_TransitionLink (ct1, ct2){
+                label = "2"
+            }
+        }
+    }
+    {Contains} ForAll copy_places {
+        LHS {
+            Pre_PetriNet/Place {
+                label = "0"
+            }
+        }
+        RHS {
+            Post_PetriNet/Place cp1 {
+                label = "0"
+            }
+            Post_PetriNet_Runtime/Place cp2 {
+                label = "1"
+                value_tokens = $
+                    Integer function value(model : Element, name : String, mapping : Element):
+                        return read_attribute(model, mapping["0"], "tokens")!
+                    $
+                value_name = $
+                    Integer function value(model : Element, name : String, mapping : Element):
+                        return read_attribute(model, mapping["0"], "name")!
+                    $
+            }
+            Post_D2R_PlaceLink (cp1, cp2){
+                label = "2"
+            }
+        }
+    }
+    {Contains} ForAll copy_P2T {
+        LHS {
+            Pre_PetriNet/Place cp2t_p{
+                label = "0"
+            }
+            Pre_PetriNet/Transition cp2t_t{
+                label = "1"
+            }
+            Pre_PetriNet/P2T (cp2t_p, cp2t_t){
+                label = "2"
+            }
+            Pre_PetriNet_Runtime/Place cp2t_p2{
+                label = "3"
+            }
+            Pre_PetriNet_Runtime/Transition cp2t_t2{
+                label = "4"
+            }
+            Pre_D2R_PlaceLink (cp2t_p, cp2t_p2){
+                label = "5"
+            }
+            Pre_D2R_TransitionLink (cp2t_t, cp2t_t2){
+                label = "6"
+            }
+        }
+        RHS {
+            Post_PetriNet/Place rhs_cp2t_p{
+                label = "0"
+            }
+            Post_PetriNet/Transition rhs_cp2t_t{
+                label = "1"
+            }
+            Post_PetriNet/P2T rhs_cp2t_p2t (rhs_cp2t_p, rhs_cp2t_t){
+                label = "2"
+            }
+            Post_PetriNet_Runtime/Place rhs_cp2t_p2 {
+                label = "3"
+            }
+            Post_PetriNet_Runtime/Transition rhs_cp2t_t2 {
+                label = "4"
+            }
+            Post_D2R_PlaceLink (rhs_cp2t_p, rhs_cp2t_p2){
+                label = "5"
+            }
+            Post_D2R_TransitionLink (rhs_cp2t_t, rhs_cp2t_t2){
+                label = "6"
+            }
+            Post_PetriNet_Runtime/P2T rhs_cp2t_p2t2(rhs_cp2t_p2, rhs_cp2t_t2) {
+                label = "7"
+                value_weight = $
+                    Integer function value(host_model : Element, name : String, mapping : Element):
+                        return read_attribute(host_model, mapping["2"], "weight")!
+                    $
             }
         }
-        {Contains} ForAll copy_P2T {
-            LHS {
-                Pre_PetriNet/Place cp2t_p{
-                    label = "0"
-                }
-                Pre_PetriNet/Transition cp2t_t{
-                    label = "1"
-                }
-                Pre_PetriNet/P2T (cp2t_p, cp2t_t){
-                    label = "2"
-                }
-                Pre_PetriNet_Runtime/Place cp2t_p2{
-                    label = "3"
-                }
-                Pre_PetriNet_Runtime/Transition cp2t_t2{
-                    label = "4"
-                }
-                Pre_D2R_PlaceLink (cp2t_p, cp2t_p2){
-                    label = "5"
-                }
-                Pre_D2R_TransitionLink (cp2t_t, cp2t_t2){
-                    label = "6"
-                }
-            }
-            RHS {
-                Post_PetriNet/Place rhs_cp2t_p{
-                    label = "0"
-                }
-                Post_PetriNet/Transition rhs_cp2t_t{
-                    label = "1"
-                }
-                Post_PetriNet/P2T rhs_cp2t_p2t (rhs_cp2t_p, rhs_cp2t_t){
-                    label = "2"
-                }
-                Post_PetriNet_Runtime/Place rhs_cp2t_p2 {
-                    label = "3"
-                }
-                Post_PetriNet_Runtime/Transition rhs_cp2t_t2 {
-                    label = "4"
-                }
-                Post_D2R_PlaceLink (rhs_cp2t_p, rhs_cp2t_p2){
-                    label = "5"
-                }
-                Post_D2R_TransitionLink (rhs_cp2t_t, rhs_cp2t_t2){
-                    label = "6"
-                }
-                Post_PetriNet_Runtime/P2T rhs_cp2t_p2t2(rhs_cp2t_p2, rhs_cp2t_t2) {
-                    label = "7"
-                    value_weight = $
-                        Integer function value(host_model : Element, name : String, mapping : Element):
-                            return read_attribute(host_model, mapping["2"], "weight")!
-                        $
-                }
+    }
+    {Contains} ForAll copy_T2P {
+        LHS {
+            Pre_PetriNet/Place ct2p_p{
+                label = "0"
+            }
+            Pre_PetriNet/Transition ct2p_t{
+                label = "1"
+            }
+            Pre_PetriNet/T2P (ct2p_t, ct2p_p){
+                label = "2"
+            }
+            Pre_PetriNet_Runtime/Place ct2p_p2{
+                label = "3"
+            }
+            Pre_PetriNet_Runtime/Transition ct2p_t2{
+                label = "4"
+            }
+            Pre_D2R_PlaceLink (ct2p_p, ct2p_p2){
+                label = "5"
+            }
+            Pre_D2R_TransitionLink (ct2p_t, ct2p_t2){
+                label = "6"
             }
         }
-        {Contains} ForAll copy_T2P {
-            LHS {
-                Pre_PetriNet/Place ct2p_p{
-                    label = "0"
-                }
-                Pre_PetriNet/Transition ct2p_t{
-                    label = "1"
-                }
-                Pre_PetriNet/T2P (ct2p_t, ct2p_p){
-                    label = "2"
-                }
-                Pre_PetriNet_Runtime/Place ct2p_p2{
-                    label = "3"
-                }
-                Pre_PetriNet_Runtime/Transition ct2p_t2{
-                    label = "4"
-                }
-                Pre_D2R_PlaceLink (ct2p_p, ct2p_p2){
-                    label = "5"
-                }
-                Pre_D2R_TransitionLink (ct2p_t, ct2p_t2){
-                    label = "6"
-                }
-            }
-            RHS {
-                Post_PetriNet/Place rhs_ct2p_p{
-                    label = "0"
-                }
-                Post_PetriNet/Transition rhs_ct2p_t{
-                    label = "1"
-                }
-                Post_PetriNet/T2P (rhs_ct2p_t, rhs_ct2p_p){
-                    label = "2"
-                }
-                Post_PetriNet_Runtime/Place rhs_ct2p_p2 {
-                    label = "3"
-                }
-                Post_PetriNet_Runtime/Transition rhs_ct2p_t2 {
-                    label = "4"
-                }
-                Post_D2R_PlaceLink (rhs_ct2p_p, rhs_ct2p_p2){
-                    label = "5"
-                }
-                Post_D2R_TransitionLink (rhs_ct2p_t, rhs_ct2p_t2){
-                    label = "6"
-                }
-                Post_PetriNet_Runtime/T2P (rhs_ct2p_t2, rhs_ct2p_p2) {
-                    label = "7"
-                    value_weight = $
-                        Integer function value(host_model : Element, name : String, mapping : Element):
-                            return read_attribute(host_model, mapping["2"], "weight")!
-                        $
-                }
+        RHS {
+            Post_PetriNet/Place rhs_ct2p_p{
+                label = "0"
+            }
+            Post_PetriNet/Transition rhs_ct2p_t{
+                label = "1"
+            }
+            Post_PetriNet/T2P (rhs_ct2p_t, rhs_ct2p_p){
+                label = "2"
+            }
+            Post_PetriNet_Runtime/Place rhs_ct2p_p2 {
+                label = "3"
+            }
+            Post_PetriNet_Runtime/Transition rhs_ct2p_t2 {
+                label = "4"
+            }
+            Post_D2R_PlaceLink (rhs_ct2p_p, rhs_ct2p_p2){
+                label = "5"
+            }
+            Post_D2R_TransitionLink (rhs_ct2p_t, rhs_ct2p_t2){
+                label = "6"
+            }
+            Post_PetriNet_Runtime/T2P (rhs_ct2p_t2, rhs_ct2p_p2) {
+                label = "7"
+                value_weight = $
+                    Integer function value(host_model : Element, name : String, mapping : Element):
+                        return read_attribute(host_model, mapping["2"], "weight")!
+                    $
             }
         }
     }
-    OnSuccess (copy_places, copy_transitions) {}
-    OnSuccess (copy_transitions, copy_P2T) {}
-    OnSuccess (copy_P2T, copy_T2P) {}
-    OnSuccess (copy_T2P, success) {}
-    OnFailure (copy_places, copy_transitions) {}
-    OnFailure (copy_transitions, copy_P2T) {}
-    OnFailure (copy_P2T, copy_T2P) {}
-    OnFailure (copy_T2P, success) {}
-    Initial (schedule, copy_places) {}
 }
-
-export annotate to models/pn_annotate
+OnSuccess (copy_places, copy_transitions) {}
+OnSuccess (copy_transitions, copy_P2T) {}
+OnSuccess (copy_P2T, copy_T2P) {}
+OnSuccess (copy_T2P, success) {}
+OnFailure (copy_places, copy_transitions) {}
+OnFailure (copy_transitions, copy_P2T) {}
+OnFailure (copy_P2T, copy_T2P) {}
+OnFailure (copy_T2P, success) {}
+Initial (schedule, copy_places) {}

+ 18 - 23
integration/code/pn_print.mvc

@@ -1,31 +1,26 @@
-import models/RAM_PetriNets_Runtime as RAM_PN_R
 include "primitives.alh"
 include "modelling.alh"
 
-RAM_PN_R print {
-    Composite schedule {
-        {Contains} Success success {}
-        {Contains} ForAll print_tokens {
-            LHS {
-                Pre_PetriNet/Place {
-                    label = "0"
-                }
+Composite schedule {
+    {Contains} Success success {}
+    {Contains} ForAll print_tokens {
+        LHS {
+            Pre_PetriNet/Place {
+                label = "0"
             }
-            RHS {
-                Post_PetriNet/Place {
-                    label = "0"
-                    action = $
-                        Void function action(model : Element, name : String, mapping : Element):
-                            output((cast_v2s(read_attribute(model, name, "name")) + " --> ") + cast_v2s(read_attribute(model, name, "tokens")))
-                            return!
-                        $
-                }
+        }
+        RHS {
+            Post_PetriNet/Place {
+                label = "0"
+                action = $
+                    Void function action(model : Element, name : String, mapping : Element):
+                        output((cast_v2s(read_attribute(model, name, "name")) + " --> ") + cast_v2s(read_attribute(model, name, "tokens")))
+                        return!
+                    $
             }
         }
     }
-    OnSuccess (print_tokens, success) {}
-    OnFailure (print_tokens, success) {}
-    Initial (schedule, print_tokens) {}
 }
-
-export print to models/pn_print
+OnSuccess (print_tokens, success) {}
+OnFailure (print_tokens, success) {}
+Initial (schedule, print_tokens) {}

+ 16 - 22
integration/code/pn_runtime.mvc

@@ -1,24 +1,18 @@
-import models/SimpleClassDiagrams as SimpleClassDiagrams
+SimpleAttribute Natural {}
+SimpleAttribute Boolean {}
+SimpleAttribute String {}
 
-SimpleClassDiagrams PetriNets_Runtime{
-    SimpleAttribute Natural {}
-    SimpleAttribute Boolean {}
-    SimpleAttribute String {}
-
-    Class Place {
-        name : String
-        tokens : Natural
-    }
-    Class Transition {
-        name : String
-        executing : Boolean
-    }
-    Association P2T (Place, Transition) {
-        weight : Natural
-    }
-    Association T2P (Transition, Place) {
-        weight : Natural
-    }
+Class Place {
+    name : String
+    tokens : Natural
+}
+Class Transition {
+    name : String
+    executing : Boolean
+}
+Association P2T (Place, Transition) {
+    weight : Natural
+}
+Association T2P (Transition, Place) {
+    weight : Natural
 }
-
-export PetriNets_Runtime to models/PetriNets_Runtime

+ 24 - 30
integration/code/pn_runtime_model.mvc

@@ -1,31 +1,25 @@
-import models/PetriNets_Runtime as PetriNets_Runtime
-
-PetriNets_Runtime pn {
-	Place p1 {
-		tokens = 1
-        name = "p1"
-	}
-	Place p2 {
-		tokens = 2
-        name = "p2"
-	}
-	Place p3 {
-		tokens = 3
-        name = "p3"
-	}
-	Transition t1 {
-		executing = False
-        name = "t1"
-	}
-	P2T (p1, t1) {
-		weight = 1
-	}
-	P2T (p2, t1) {
-		weight = 1
-	}
-	T2P (t1, p3) {
-		weight = 2
-	}
+Place p1 {
+	tokens = 1
+name = "p1"
+}
+Place p2 {
+	tokens = 2
+name = "p2"
+}
+Place p3 {
+	tokens = 3
+name = "p3"
+}
+Transition t1 {
+	executing = False
+name = "t1"
+}
+P2T (p1, t1) {
+	weight = 1
+}
+P2T (p2, t1) {
+	weight = 1
+}
+T2P (t1, p3) {
+	weight = 2
 }
-
-export pn to models/pn

+ 161 - 166
integration/code/pn_runtime_to_design.mvc

@@ -1,179 +1,174 @@
-import models/RAM_PetriNet_Design_Runtime as RAM_PN_DR
 include "primitives.alh"
 include "modelling.alh"
 
-RAM_PN_DR annotate {
-    Composite schedule {
-        {Contains} Failure failure {}
-        {Contains} Success success {}
-        {Contains} ForAll copy_transitions {
-            LHS {
-                Pre_PetriNet_Runtime/Transition {
-                    label = "0"
-                }
-            }
-            RHS {
-                Post_PetriNet_Runtime/Transition ct1 {
-                    label = "0"
-                }
-                Post_PetriNet/Transition ct2 {
-                    label = "1"
-                    value_name = $
-                        Integer function value(model : Element, name : String, mapping : Element):
-                            return read_attribute(model, mapping["0"], "name")!
-                        $
-                }
-                Post_R2D_TransitionLink (ct1, ct2){
-                    label = "2"
-                }
+Composite schedule {
+    {Contains} Failure failure {}
+    {Contains} Success success {}
+    {Contains} ForAll copy_transitions {
+        LHS {
+            Pre_PetriNet_Runtime/Transition {
+                label = "0"
             }
         }
-        {Contains} ForAll copy_places {
-            LHS {
-                Pre_PetriNet_Runtime/Place {
-                    label = "0"
-                }
-            }
-            RHS {
-                Post_PetriNet_Runtime/Place cp1 {
-                    label = "0"
-                }
-                Post_PetriNet/Place cp2 {
-                    label = "1"
-                    value_tokens = $
-                        Integer function value(host_model : Element, name : String, mapping : Element):
-                            return read_attribute(host_model, mapping["0"], "tokens")!
-                        $
-                    value_name = $
-                        String function value(host_model : Element, name : String, mapping : Element):
-                            return read_attribute(host_model, mapping["0"], "name")!
-                        $
-                }
-                Post_R2D_PlaceLink (cp1, cp2){
-                    label = "2"
-                }
+        RHS {
+            Post_PetriNet_Runtime/Transition ct1 {
+                label = "0"
+            }
+            Post_PetriNet/Transition ct2 {
+                label = "1"
+                value_name = $
+                    Integer function value(model : Element, name : String, mapping : Element):
+                        return read_attribute(model, mapping["0"], "name")!
+                    $
+            }
+            Post_R2D_TransitionLink (ct1, ct2){
+                label = "2"
+            }
+        }
+    }
+    {Contains} ForAll copy_places {
+        LHS {
+            Pre_PetriNet_Runtime/Place {
+                label = "0"
+            }
+        }
+        RHS {
+            Post_PetriNet_Runtime/Place cp1 {
+                label = "0"
+            }
+            Post_PetriNet/Place cp2 {
+                label = "1"
+                value_tokens = $
+                    Integer function value(host_model : Element, name : String, mapping : Element):
+                        return read_attribute(host_model, mapping["0"], "tokens")!
+                    $
+                value_name = $
+                    String function value(host_model : Element, name : String, mapping : Element):
+                        return read_attribute(host_model, mapping["0"], "name")!
+                    $
+            }
+            Post_R2D_PlaceLink (cp1, cp2){
+                label = "2"
+            }
+        }
+    }
+    {Contains} ForAll copy_P2T {
+        LHS {
+            Pre_PetriNet_Runtime/Place cp2t_p{
+                label = "0"
+            }
+            Pre_PetriNet_Runtime/Transition cp2t_t{
+                label = "1"
+            }
+            Pre_PetriNet_Runtime/P2T (cp2t_p, cp2t_t){
+                label = "2"
+            }
+            Pre_PetriNet/Place cp2t_p2{
+                label = "3"
+            }
+            Pre_PetriNet/Transition cp2t_t2{
+                label = "4"
+            }
+            Pre_R2D_PlaceLink (cp2t_p, cp2t_p2){
+                label = "5"
+            }
+            Pre_R2D_TransitionLink (cp2t_t, cp2t_t2){
+                label = "6"
+            }
+        }
+        RHS {
+            Post_PetriNet_Runtime/Place rhs_cp2t_p{
+                label = "0"
+            }
+            Post_PetriNet_Runtime/Transition rhs_cp2t_t{
+                label = "1"
+            }
+            Post_PetriNet_Runtime/P2T rhs_cp2t_p2t (rhs_cp2t_p, rhs_cp2t_t){
+                label = "2"
+            }
+            Post_PetriNet/Place rhs_cp2t_p2 {
+                label = "3"
+            }
+            Post_PetriNet/Transition rhs_cp2t_t2 {
+                label = "4"
+            }
+            Post_R2D_PlaceLink (rhs_cp2t_p, rhs_cp2t_p2){
+                label = "5"
+            }
+            Post_R2D_TransitionLink (rhs_cp2t_t, rhs_cp2t_t2){
+                label = "6"
+            }
+            Post_PetriNet/P2T rhs_cp2t_p2t2(rhs_cp2t_p2, rhs_cp2t_t2) {
+                label = "7"
+                value_weight = $
+                    Integer function value(host_model : Element, name : String, mapping : Element):
+                        return read_attribute(host_model, mapping["2"], "weight")!
+                    $
             }
         }
-        {Contains} ForAll copy_P2T {
-            LHS {
-                Pre_PetriNet_Runtime/Place cp2t_p{
-                    label = "0"
-                }
-                Pre_PetriNet_Runtime/Transition cp2t_t{
-                    label = "1"
-                }
-                Pre_PetriNet_Runtime/P2T (cp2t_p, cp2t_t){
-                    label = "2"
-                }
-                Pre_PetriNet/Place cp2t_p2{
-                    label = "3"
-                }
-                Pre_PetriNet/Transition cp2t_t2{
-                    label = "4"
-                }
-                Pre_R2D_PlaceLink (cp2t_p, cp2t_p2){
-                    label = "5"
-                }
-                Pre_R2D_TransitionLink (cp2t_t, cp2t_t2){
-                    label = "6"
-                }
-            }
-            RHS {
-                Post_PetriNet_Runtime/Place rhs_cp2t_p{
-                    label = "0"
-                }
-                Post_PetriNet_Runtime/Transition rhs_cp2t_t{
-                    label = "1"
-                }
-                Post_PetriNet_Runtime/P2T rhs_cp2t_p2t (rhs_cp2t_p, rhs_cp2t_t){
-                    label = "2"
-                }
-                Post_PetriNet/Place rhs_cp2t_p2 {
-                    label = "3"
-                }
-                Post_PetriNet/Transition rhs_cp2t_t2 {
-                    label = "4"
-                }
-                Post_R2D_PlaceLink (rhs_cp2t_p, rhs_cp2t_p2){
-                    label = "5"
-                }
-                Post_R2D_TransitionLink (rhs_cp2t_t, rhs_cp2t_t2){
-                    label = "6"
-                }
-                Post_PetriNet/P2T rhs_cp2t_p2t2(rhs_cp2t_p2, rhs_cp2t_t2) {
-                    label = "7"
-                    value_weight = $
-                        Integer function value(host_model : Element, name : String, mapping : Element):
-                            return read_attribute(host_model, mapping["2"], "weight")!
-                        $
-                }
+    }
+    {Contains} ForAll copy_T2P {
+        LHS {
+            Pre_PetriNet_Runtime/Place ct2p_p{
+                label = "0"
+            }
+            Pre_PetriNet_Runtime/Transition ct2p_t{
+                label = "1"
+            }
+            Pre_PetriNet_Runtime/T2P (ct2p_t, ct2p_p){
+                label = "2"
+            }
+            Pre_PetriNet/Place ct2p_p2{
+                label = "3"
+            }
+            Pre_PetriNet/Transition ct2p_t2{
+                label = "4"
+            }
+            Pre_R2D_PlaceLink (ct2p_p, ct2p_p2){
+                label = "5"
+            }
+            Pre_R2D_TransitionLink (ct2p_t, ct2p_t2){
+                label = "6"
             }
         }
-        {Contains} ForAll copy_T2P {
-            LHS {
-                Pre_PetriNet_Runtime/Place ct2p_p{
-                    label = "0"
-                }
-                Pre_PetriNet_Runtime/Transition ct2p_t{
-                    label = "1"
-                }
-                Pre_PetriNet_Runtime/T2P (ct2p_t, ct2p_p){
-                    label = "2"
-                }
-                Pre_PetriNet/Place ct2p_p2{
-                    label = "3"
-                }
-                Pre_PetriNet/Transition ct2p_t2{
-                    label = "4"
-                }
-                Pre_R2D_PlaceLink (ct2p_p, ct2p_p2){
-                    label = "5"
-                }
-                Pre_R2D_TransitionLink (ct2p_t, ct2p_t2){
-                    label = "6"
-                }
-            }
-            RHS {
-                Post_PetriNet_Runtime/Place rhs_ct2p_p{
-                    label = "0"
-                }
-                Post_PetriNet_Runtime/Transition rhs_ct2p_t{
-                    label = "1"
-                }
-                Post_PetriNet_Runtime/T2P (rhs_ct2p_t, rhs_ct2p_p){
-                    label = "2"
-                }
-                Post_PetriNet/Place rhs_ct2p_p2 {
-                    label = "3"
-                }
-                Post_PetriNet/Transition rhs_ct2p_t2 {
-                    label = "4"
-                }
-                Post_R2D_PlaceLink (rhs_ct2p_p, rhs_ct2p_p2){
-                    label = "5"
-                }
-                Post_R2D_TransitionLink (rhs_ct2p_t, rhs_ct2p_t2){
-                    label = "6"
-                }
-                Post_PetriNet/T2P (rhs_ct2p_t2, rhs_ct2p_p2) {
-                    label = "7"
-                    value_weight = $
-                        Integer function value(host_model : Element, name : String, mapping : Element):
-                            return read_attribute(host_model, mapping["2"], "weight")!
-                        $
-                }
+        RHS {
+            Post_PetriNet_Runtime/Place rhs_ct2p_p{
+                label = "0"
+            }
+            Post_PetriNet_Runtime/Transition rhs_ct2p_t{
+                label = "1"
+            }
+            Post_PetriNet_Runtime/T2P (rhs_ct2p_t, rhs_ct2p_p){
+                label = "2"
+            }
+            Post_PetriNet/Place rhs_ct2p_p2 {
+                label = "3"
+            }
+            Post_PetriNet/Transition rhs_ct2p_t2 {
+                label = "4"
+            }
+            Post_R2D_PlaceLink (rhs_ct2p_p, rhs_ct2p_p2){
+                label = "5"
+            }
+            Post_R2D_TransitionLink (rhs_ct2p_t, rhs_ct2p_t2){
+                label = "6"
+            }
+            Post_PetriNet/T2P (rhs_ct2p_t2, rhs_ct2p_p2) {
+                label = "7"
+                value_weight = $
+                    Integer function value(host_model : Element, name : String, mapping : Element):
+                        return read_attribute(host_model, mapping["2"], "weight")!
+                    $
             }
         }
     }
-    OnSuccess (copy_places, copy_transitions) {}
-    OnSuccess (copy_transitions, copy_P2T) {}
-    OnSuccess (copy_P2T, copy_T2P) {}
-    OnSuccess (copy_T2P, success) {}
-    OnFailure (copy_places, copy_transitions) {}
-    OnFailure (copy_transitions, copy_P2T) {}
-    OnFailure (copy_P2T, copy_T2P) {}
-    OnFailure (copy_T2P, success) {}
-    Initial (schedule, copy_places) {}
 }
-
-export annotate to models/pn_annotate
+OnSuccess (copy_places, copy_transitions) {}
+OnSuccess (copy_transitions, copy_P2T) {}
+OnSuccess (copy_P2T, copy_T2P) {}
+OnSuccess (copy_T2P, success) {}
+OnFailure (copy_places, copy_transitions) {}
+OnFailure (copy_transitions, copy_P2T) {}
+OnFailure (copy_P2T, copy_T2P) {}
+OnFailure (copy_T2P, success) {}
+Initial (schedule, copy_places) {}

+ 0 - 153
integration/code/pn_semantics.alc

@@ -1,153 +0,0 @@
-include "primitives.alh"
-include "modelling.alh"
-include "object_operations.alh"
-include "library.alh"
-include "conformance_scd.alh"
-
-Void function petrinet_enabled(model : Element):
-	Element set_enabled
-	set_enabled = petrinet_enabled_set(model)
-	output("Enabled transitions:")
-	while (0 < read_nr_out(set_enabled)):
-		output(set_pop(set_enabled))
-	return!
-
-Element function petrinet_enabled_set(model : Element):
-	Element all_transitions
-	Element enabled_transitions
-	String under_study
-	Element in_arcs
-	String arc_under_study
-	Boolean enabled
-
-	all_transitions = allInstances(model, "Transition")
-	enabled_transitions = create_node()
-
-	while (0 < read_nr_out(all_transitions)):
-		under_study = set_pop(all_transitions)
-		enabled = True
-
-		// Find all incoming transitions
-		in_arcs = allIncomingAssociationInstances(model, under_study, "P2T")
-
-		while (0 < read_nr_out(in_arcs)):
-			arc_under_study = set_pop(in_arcs)
-
-			Integer present_tokens
-			Integer required_tokens
-			required_tokens = read_attribute(model, arc_under_study, "weight")
-			log("Weight: " + cast_i2s(required_tokens))
-			present_tokens = read_attribute(model, reverseKeyLookup(model["model"], read_edge_src(model["model"][arc_under_study])), "tokens")
-			log("Tokens: " + cast_i2s(present_tokens))
-			if (present_tokens < required_tokens):
-				// Less tokens than required, so disable the transition completely
-				enabled = False
-
-		if (enabled):
-			set_add(enabled_transitions, under_study)
-
-	log("Got all enabled transitions!")
-	return enabled_transitions!
-
-Void function petrinet_fire(model : Element):
-	output("Transition to fire?")
-	String transition
-	transition = input()
-	if (dict_in(model["model"], transition)):
-		if (set_in(petrinet_enabled_set(model), transition)):
-			Element workset
-			String working_place
-			String working_arc
-			Integer new_value
-
-			// Consume tokens
-			workset = allIncomingAssociationInstances(model, transition, "P2T")
-			while (0 < read_nr_out(workset)):
-				working_arc = set_pop(workset)
-				working_place = reverseKeyLookup(model["model"], read_edge_src(model["model"][working_arc]))
-				new_value = integer_subtraction(read_attribute(model, working_place, "tokens"), read_attribute(model, working_arc, "weight"))
-				unset_attribute(model, working_place, "tokens")
-				instantiate_attribute(model, working_place, "tokens", new_value)
-				output((("  " + working_place) + ": ") + cast_i2s(read_attribute(model, working_place, "tokens")))
-
-			// Add tokens
-			workset = allOutgoingAssociationInstances(model, transition, "T2P")
-			while (0 < read_nr_out(workset)):
-				working_arc = set_pop(workset)
-				working_place = reverseKeyLookup(model["model"], read_edge_dst(model["model"][working_arc]))
-				new_value = integer_addition(read_attribute(model, working_place, "tokens"), read_attribute(model, working_arc, "weight"))
-				unset_attribute(model, working_place, "tokens")
-				instantiate_attribute(model, working_place, "tokens", new_value)
-				output((("  " + working_place) + ": ") + cast_i2s(read_attribute(model, working_place, "tokens")))
-			output("Transition fired!")
-		else:
-			output("Cannot fire if not enabled; aborting")
-	else:
-		output("Unknown transition; aborting")
-	return!
-
-Void function petrinet_list(model : Element):
-	Element keys 
-	Element typemap
-	Element place
-	String name
-
-	keys = dict_keys(model["model"])
-	typemap = model["type_mapping"]
-	place = model["metamodel"]["model"]["Place"]
-
-	while (list_len(keys) > 0):
-		name = set_pop(keys)
-		if (element_eq(dict_read_node(typemap, model["model"][name]), place)):
-			// Found a place
-			output((name + ": ") + cast_i2s(read_attribute(model, name, "tokens")))
-	return!
-
-Void function main():
-	Element model
-	String verify_result
-
-	while (True):
-		output("Which model do you want to execute with petri net semantics?")
-		model = import_node(input())
-
-		if (element_eq(model, read_root())):
-			output("Could not find model; aborting")
-		elif (element_neq(model["metamodel"], import_node("models/PetriNets"))):
-			output("Not a PetriNets model; aborting")
-		else:
-			verify_result = conformance_scd(model)
-			if (verify_result == "OK"):
-				output("Model OK!")
-				execute_petrinet(model)
-			else:
-				output("Non-conforming model: " + verify_result)
-
-	return!
-
-Void function execute_petrinet(model : Element):
-	String cmd
-	while (True):
-		output("Which operation do you want to execute?")
-		cmd = input()
-
-		if (cmd == "help"):
-			output("Supported operations:")
-			output("  help    -- this information")
-			output("  enabled -- list the enabled transitions")
-			output("  fire    -- fire a transition")
-			output("  list    -- list the state of the petrinet")
-			output("  exit    -- select another model")
-		elif (cmd == "enabled"):
-			petrinet_enabled(model)
-		elif (cmd == "fire"):
-			petrinet_fire(model)
-		elif (cmd == "list"):
-			petrinet_list(model)
-		elif (cmd == "exit"):
-			return!
-		else:
-			output("Did not understand command!")
-			output("Use 'help' for a list of available options")
-
-	return!

+ 120 - 125
integration/code/pn_simulate.mvc

@@ -1,140 +1,135 @@
-import models/RAM_PetriNet_Runtime_Runtime as RAM_PN_R
 include "primitives.alh"
 include "modelling.alh"
 
-RAM_PN_R s {
-    Composite schedule {
-        {Contains} Failure failure {}
-        {Contains} Success success {}
-        {Contains} Atomic mark {
-            LHS {
-                Pre_PetriNet_Runtime/Transition {
-                    label = "1"
-                }
-            }
-            NAC {
-				Pre_PetriNet_Runtime/Transition mark_nac_t {
-					label = "1"
-				}
-				Pre_PetriNet_Runtime/Place mark_nac_p{
-					label = "10"
-				}
-				Pre_PetriNet_Runtime/P2T (mark_nac_p, mark_nac_t){
-					label = "11"
-				}
-				constraint = $
-					Boolean function constraint(host_model : Element, mapping : Element):
-						Integer tokens
-						Integer weight
-						tokens = read_attribute(host_model, mapping["10"], "tokens")
-						weight = read_attribute(host_model, mapping["11"], "weight")
+Composite schedule {
+    {Contains} Failure failure {}
+    {Contains} Success success {}
+    {Contains} Atomic mark {
+        LHS {
+            Pre_PetriNet_Runtime/Transition {
+                label = "1"
+            }
+        }
+        NAC {
+    			Pre_PetriNet_Runtime/Transition mark_nac_t {
+    				label = "1"
+    			}
+    			Pre_PetriNet_Runtime/Place mark_nac_p{
+    				label = "10"
+    			}
+    			Pre_PetriNet_Runtime/P2T (mark_nac_p, mark_nac_t){
+    				label = "11"
+    			}
+    			constraint = $
+    				Boolean function constraint(host_model : Element, mapping : Element):
+    					Integer tokens
+    					Integer weight
+    					tokens = read_attribute(host_model, mapping["10"], "tokens")
+    					weight = read_attribute(host_model, mapping["11"], "weight")
                         return (tokens < weight)!
-					$
+    				$
+        }
+        RHS {
+            Post_PetriNet_Runtime/Transition {
+                label = "1"
+                value_executing = $
+                    Boolean function value(host_model : Element, name : String, mapping : Element):
+                        return True!
+                    $
+            }
+        }
+    }
+    {Contains} ForAll consume {
+        LHS {
+            Pre_PetriNet_Runtime/Transition lhs_consume_t{
+                label = "0"
+                constraint_executing = $
+                    Boolean function constraint(value : Boolean):
+                        return value!
+                    $
+            }
+            Pre_PetriNet_Runtime/Place lhs_consume_p{
+                label = "1"
+            }
+            Pre_PetriNet_Runtime/P2T lhs_consume_p2t(lhs_consume_p, lhs_consume_t){
+                label = "2"
+            }
+        }
+        RHS {
+            Post_PetriNet_Runtime/Transition rhs_consume_t {
+                label = "0"
             }
-            RHS {
-                Post_PetriNet_Runtime/Transition {
-                    label = "1"
-                    value_executing = $
-                        Boolean function value(host_model : Element, name : String, mapping : Element):
-                            return True!
-                        $
-                }
+            Post_PetriNet_Runtime/Place rhs_consume_p {
+                label = "1"
+                value_tokens = $
+                    Integer function value(host_model : Element, name : String, mapping : Element):
+                        return integer_subtraction(read_attribute(host_model, name, "tokens"), read_attribute(host_model, mapping["2"], "weight"))!
+                    $
+            }
+            Post_PetriNet_Runtime/P2T (rhs_consume_p, rhs_consume_t){
+                label = "2"
+            }
+        }
+    }
+    {Contains} ForAll produce {
+        LHS {
+            Pre_PetriNet_Runtime/Transition lhs_produce_t{
+                label = "0"
+                constraint_executing = $
+                    Boolean function constraint(value : Boolean):
+                        return value!
+                    $
+            }
+            Pre_PetriNet_Runtime/Place lhs_produce_p{
+                label = "1"
+            }
+            Pre_PetriNet_Runtime/T2P (lhs_produce_t, lhs_produce_p){
+                label = "2"
             }
         }
-        {Contains} ForAll consume {
-            LHS {
-                Pre_PetriNet_Runtime/Transition lhs_consume_t{
-                    label = "0"
-                    constraint_executing = $
-                        Boolean function constraint(value : Boolean):
-                            return value!
-                        $
-                }
-                Pre_PetriNet_Runtime/Place lhs_consume_p{
-                    label = "1"
-                }
-                Pre_PetriNet_Runtime/P2T lhs_consume_p2t(lhs_consume_p, lhs_consume_t){
-                    label = "2"
-                }
-            }
-            RHS {
-                Post_PetriNet_Runtime/Transition rhs_consume_t {
-                    label = "0"
-                }
-                Post_PetriNet_Runtime/Place rhs_consume_p {
-                    label = "1"
-                    value_tokens = $
-                        Integer function value(host_model : Element, name : String, mapping : Element):
-                            return integer_subtraction(read_attribute(host_model, name, "tokens"), read_attribute(host_model, mapping["2"], "weight"))!
-                        $
-                }
-                Post_PetriNet_Runtime/P2T (rhs_consume_p, rhs_consume_t){
-                    label = "2"
-                }
+        RHS {
+            Post_PetriNet_Runtime/Transition rhs_produce_t{
+                label = "0"
+            }
+            Post_PetriNet_Runtime/Place rhs_produce_p{
+                label = "1"
+                value_tokens = $
+                    Integer function value(host_model : Element, name : String, mapping : Element):
+                        return integer_addition(read_attribute(host_model, name, "tokens"), read_attribute(host_model, mapping["2"], "weight"))!
+                    $
+            }
+            Post_PetriNet_Runtime/T2P (rhs_produce_t, rhs_produce_p){
+                label = "2"
             }
         }
-        {Contains} ForAll produce {
-            LHS {
-                Pre_PetriNet_Runtime/Transition lhs_produce_t{
-                    label = "0"
-                    constraint_executing = $
-                        Boolean function constraint(value : Boolean):
-                            return value!
-                        $
-                }
-                Pre_PetriNet_Runtime/Place lhs_produce_p{
-                    label = "1"
-                }
-                Pre_PetriNet_Runtime/T2P (lhs_produce_t, lhs_produce_p){
-                    label = "2"
-                }
-            }
-            RHS {
-                Post_PetriNet_Runtime/Transition rhs_produce_t{
-                    label = "0"
-                }
-                Post_PetriNet_Runtime/Place rhs_produce_p{
-                    label = "1"
-                    value_tokens = $
-                        Integer function value(host_model : Element, name : String, mapping : Element):
-                            return integer_addition(read_attribute(host_model, name, "tokens"), read_attribute(host_model, mapping["2"], "weight"))!
-                        $
-                }
-                Post_PetriNet_Runtime/T2P (rhs_produce_t, rhs_produce_p){
-                    label = "2"
-                }
+    }
+    {Contains} Atomic unmark_transition {
+        LHS {
+            Pre_PetriNet_Runtime/Transition {
+                label = "0"
+                constraint_executing = $
+                    Boolean function constraint(value : Boolean):
+                        return value!
+                    $
             }
         }
-        {Contains} Atomic unmark_transition {
-            LHS {
-                Pre_PetriNet_Runtime/Transition {
-                    label = "0"
-                    constraint_executing = $
-                        Boolean function constraint(value : Boolean):
-                            return value!
-                        $
-                }
-            }
-            RHS {
-                Post_PetriNet_Runtime/Transition {
-                    label = "0"
-                    value_executing = $
-                        Boolean function value(host_model : Element, name : String, mapping : Element):
-                            return False!
-                        $
-                }
+        RHS {
+            Post_PetriNet_Runtime/Transition {
+                label = "0"
+                value_executing = $
+                    Boolean function value(host_model : Element, name : String, mapping : Element):
+                        return False!
+                    $
             }
         }
     }
-    OnSuccess (mark, consume) {}
-    OnFailure (mark, failure) {}
-    OnSuccess (consume, produce) {}
-    OnFailure (consume, produce) {}
-    OnSuccess (produce, unmark_transition) {}
-    OnFailure (produce, unmark_transition) {}
-    OnSuccess (unmark_transition, success) {}
-    OnFailure (unmark_transition, failure) {}
-    Initial (schedule, mark) {}
 }
-
-export s to models/pn_simulate
+OnSuccess (mark, consume) {}
+OnFailure (mark, failure) {}
+OnSuccess (consume, produce) {}
+OnFailure (consume, produce) {}
+OnSuccess (produce, unmark_transition) {}
+OnFailure (produce, unmark_transition) {}
+OnSuccess (unmark_transition, success) {}
+OnFailure (unmark_transition, failure) {}
+Initial (schedule, mark) {}

+ 0 - 91
integration/code/ramified_petrinets.mvc

@@ -1,91 +0,0 @@
-SCD Pre_PetriNets {
-    // Add AL MM
-
-    Class LHS{
-        constraint? : Expression
-        upper_cardinality = 1
-        lower_cardinality = 1
-    }
-    Class NAC{}
-    Class Pre_Element{
-        label : String
-        constraint? : Expression
-    }
-    Association (LHS, Pre_Element)
-    Association (NAC, Pre_Element){
-        target_lower_cardinality = 1
-    }
-
-    Class Pre_Place{}
-    Class Pre_Transition{}
-    Class Pre_Natural{}
-
-    Association Pre_P2T(Pre_Place, Pre_Transition) {}
-    Association Pre_T2P(Pre_Transition, Pre_Place) {}
-
-    Association Pre_Place_tokens(Pre_Place, Pre_Natural) {
-        name = "Pre_tokens"
-        target_upper_cardinality = 1
-    }
-    Association Pre_P2T_weight(Pre_P2T, Pre_Natural) {
-        name = "Pre_weight"
-        target_upper_cardinality = 1
-    }
-    Association Pre_T2P_weight(Pre_T2P, Pre_Natural) {
-        name = "Pre_weight"
-        target_upper_cardinality = 1
-    }
-
-    Inheritance (Pre_Place, Pre_Element) {}
-    Inheritance (Pre_Natural, Pre_Element) {}
-    Inheritance (Pre_Transition, Pre_Element) {}
-    Inheritance (Pre_P2T, Pre_Element) {}
-    Inheritance (Pre_Place_tokens, Pre_Element) {}
-    Inheritance (Pre_P2T_weight, Pre_Element) {}
-    Inheritance (Pre_T2P_weight, Pre_Element) {}
-}
-
-SCD Post_PetriNets{
-    // Add AL MM
-
-    Class RHS{
-        action : FunctionDefinition
-        upper_cardinality = 1
-        lower_cardinality = 1
-    }
-
-    Class Post_Element {
-        label : String
-        value? : Expression
-    }
-
-    Class Post_Place{}
-    Class Post_Transitions{}
-    Class Post_Natural{}
-
-    Association Post_P2T(Post_Place, Post_Transition) {}
-    Association Post_T2P(Post_Transition, Post_Place) {}
-
-    Association (Post_Place, Post_Natural) {
-        name = "Post_tokens"
-        target_upper_cardinality = 1
-    }
-
-    Association (Post_P2T, Post_Natural) {
-        name = "Post_weight"
-        target_upper_cardinality = 1
-    }
-
-    Association (Post_T2P, Post_Natural) {
-        name = "Post_weight"
-        target_upper_cardinality = 1
-    }
-
-    Inheritance (Post_Place, Post_Element) {}
-    Inheritance (Post_Natural, Post_Element) {}
-    Inheritance (Post_Transition, Post_Element) {}
-    Inheritance (Post_P2T, Post_Element) {}
-    Inheritance (Post_Place_tokens, Post_Element) {}
-    Inheritance (Post_P2T_weight, Post_Element) {}
-    Inheritance (Post_T2P_weight, Post_Element) {}
-}

+ 51 - 53
integration/code/reachability_graph.mvc

@@ -2,63 +2,61 @@ include "primitives.alh"
 include "object_operations.alh"
 include "modelling.alh"
 
-SimpleClassDiagrams ReachabilityGraph {
-    SimpleAttribute String {}
-    SimpleAttribute Natural {}
-    SimpleAttribute Boolean {}
+SimpleAttribute String {}
+SimpleAttribute Natural {}
+SimpleAttribute Boolean {}
 
-    Class State {
-        name : String
-        error : Boolean
-    }
-    Class InitialState : State {
-        lower_cardinality = 1
-        upper_cardinality = 1
-    }
-
-    Class Place {
-        name : String
-        tokens : Natural
-    }
-    Association Transition (State, State) {
-        name : String
-    }
-    Association Contains (State, Place) {}
+Class State {
+    name : String
+    error : Boolean
+}
+Class InitialState : State {
+    lower_cardinality = 1
+    upper_cardinality = 1
+}
 
-    GlobalConstraint {
-        global_constraint = $
-            String function constraint(model : Element):
-                Element states
-                Element places
-                String state
-                String place
-                Element expected
-                Element got
+Class Place {
+    name : String
+    tokens : Natural
+}
+Association Transition (State, State) {
+    name : String
+}
+Association Contains (State, Place) {}
 
-                states = allInstances(model, "State")
+GlobalConstraint {
+    global_constraint = $
+        String function constraint(model : Element):
+            Element states
+            Element places
+            String state
+            String place
+            Element expected
+            Element got
 
-                if (read_nr_out(states) > 0):
-                    expected = create_node()
-                    state = set_pop(states)
-                    places = allAssociationDestinations(model, state, "Contains")
-                    while (read_nr_out(places)):
-                        place = set_pop(places)
-                        set_add(expected, read_attribute(model, place, "name"))
-                else:
-                    return "OK"!
-                
-                while (read_nr_out(states) > 0):
-                    got = create_node()
-                    state = set_pop(states)
-                    places = allAssociationDestinations(model, state, "Contains")
-                    while (read_nr_out(places)):
-                        place = set_pop(places)
-                        set_add(got, read_attribute(model, place, "name"))
+            states = allInstances(model, "State")
 
-                    if (bool_not(set_equality(got, expected))):
-                        return "States don't all agree on the set of places"!
-                
+            if (read_nr_out(states) > 0):
+                expected = create_node()
+                state = set_pop(states)
+                places = allAssociationDestinations(model, state, "Contains")
+                while (read_nr_out(places)):
+                    place = set_pop(places)
+                    set_add(expected, read_attribute(model, place, "name"))
+            else:
                 return "OK"!
-            $
-    }
+            
+            while (read_nr_out(states) > 0):
+                got = create_node()
+                state = set_pop(states)
+                places = allAssociationDestinations(model, state, "Contains")
+                while (read_nr_out(places)):
+                    place = set_pop(places)
+                    set_add(got, read_attribute(model, place, "name"))
+
+                if (bool_not(set_equality(got, expected))):
+                    return "States don't all agree on the set of places"!
+            
+            return "OK"!
+        $
 }

+ 184 - 0
integration/code/reachability_subfunction.alc

@@ -0,0 +1,184 @@
+include "primitives.alh"
+include "modelling.alh"
+include "object_operations.alh"
+
+Boolean function main(model : Element):
+	Element workset
+	Element transition_vectors_produce
+	Element transition_vectors_consume
+	Element all_transitions
+	Element all_transitions_original
+	Element tv
+	Element links
+	Element mappings
+	Element reachable_states
+	Element keys
+	String transition
+	String new_transition
+	String state
+	String name
+	String link
+	String place
+	String key
+	Integer link_weight
+	Integer initial
+	Integer state_id
+	Integer next_id
+	Boolean possible
+	Element all_places
+	Element dict_repr
+	Element new_dict_repr
+	Element work_unit
+
+	Element cache
+	cache = create_node()
+
+	// Create a dictionary representation for each transition
+	transition_vectors_produce = create_node()
+	transition_vectors_consume = create_node()
+	all_transitions = allInstances(model, "PetriNet/Transition")
+	while (read_nr_out(all_transitions) > 0):
+		transition = set_pop(all_transitions)
+
+		tv = create_node()
+		links = allIncomingAssociationInstances(model, transition, "PetriNet/P2T")
+		while (read_nr_out(links) > 0):
+			link = set_pop(links)
+			name = reverseKeyLookup(model["model"], read_edge_src(model["model"][link]))
+			link_weight = read_attribute(model, link, "weight")
+			dict_add_fast(tv, name, link_weight)
+		dict_add_fast(transition_vectors_consume, transition, tv)
+
+		tv = create_node()
+		links = allOutgoingAssociationInstances(model, transition, "PetriNet/T2P")
+		while (read_nr_out(links) > 0):
+			link = set_pop(links)
+			name = reverseKeyLookup(model["model"], read_edge_dst(model["model"][link]))
+			link_weight = read_attribute(model, link, "weight")
+			dict_add_fast(tv, name, link_weight)
+		dict_add_fast(transition_vectors_produce, transition, tv)
+
+	workset = create_node()
+
+	all_places = allInstances(model, "PetriNet/Place")
+	dict_repr = create_node()
+	while (read_nr_out(all_places) > 0):
+		place = set_pop(all_places)
+		dict_add_fast(dict_repr, place, read_attribute(model, place, "tokens"))
+
+	all_transitions_original = allInstances(model, "PetriNet/Transition")
+
+	mappings = create_node()
+	state_id = 0
+	next_id = 1
+	reachable_states = create_node()
+	dict_add_fast(reachable_states, state_id, dict_repr)
+	dict_add_fast(mappings, state_id, create_node())
+	set_add(workset, state_id)
+
+	// And add in the model itself
+	state = create_state(model, cast_i2s(state_id), dict_repr, cache, True)
+
+	while (read_nr_out(workset) > 0):
+		state_id = set_pop(workset)
+
+		dict_repr = reachable_states[state_id]
+
+		// Compute how the PN behaves with this specific state
+		// For this, we fetch all transitions and check if they are enabled
+		all_transitions = set_copy(all_transitions_original)
+		while (read_nr_out(all_transitions) > 0):
+			transition = set_pop(all_transitions)
+
+			keys = dict_keys(transition_vectors_consume[transition])
+			possible = True
+			while (read_nr_out(keys) > 0):
+				key = set_pop(keys)
+
+				// Compare the values in the state with those consumed by the transition
+				if (integer_lt(dict_repr[key], transition_vectors_consume[transition][key])):
+					// Impossible transition, so discard this one
+					possible = False
+					break!
+
+			if (possible):
+				new_dict_repr = dict_copy(dict_repr)
+				// Transition can execute, so compute and add the new state based on the consume/produce vectors
+				keys = dict_keys(transition_vectors_consume[transition])
+				while (read_nr_out(keys) > 0):
+					key = set_pop(keys)
+					dict_overwrite(new_dict_repr, key, integer_subtraction(new_dict_repr[key], transition_vectors_consume[transition][key]))
+
+				keys = dict_keys(transition_vectors_produce[transition])
+				while (read_nr_out(keys) > 0):
+					key = set_pop(keys)
+					dict_overwrite(new_dict_repr, key, integer_addition(new_dict_repr[key], transition_vectors_produce[transition][key]))
+
+				// Check if this state already has an associated ID
+				Integer other_state_id
+				Integer target_id
+
+				keys = dict_keys(reachable_states)
+				target_id = -1
+				Float start
+				while (read_nr_out(keys) > 0):
+					other_state_id = set_pop(keys)
+
+					if (dict_eq(reachable_states[other_state_id], new_dict_repr)):
+						target_id = other_state_id
+						break!
+
+				if (target_id == -1):
+					// New state
+					target_id = next_id
+					next_id = next_id + 1
+
+					// Add to all data structures
+					dict_add_fast(reachable_states, target_id, new_dict_repr)
+					dict_add_fast(mappings, target_id, create_node())
+					set_add(workset, target_id)
+
+					// And add in the model itself
+					create_state(model, cast_i2s(target_id), new_dict_repr, cache, False)
+
+				// Anyway, we have found a transition, which we should store
+				dict_add_fast(mappings[state_id], transition, target_id)
+
+				// And also store it in the model itself
+				new_transition = instantiate_link(model, "ReachabilityGraph/Transition", "", cast_i2s(state_id), cast_i2s(target_id))
+				instantiate_attribute(model, new_transition, "name", read_attribute(model, transition, "name"))
+
+	log("# reachable states: " + cast_v2s(next_id))
+	return True!
+
+String function create_state(model : Element, name : String, dict_repr : Element, cache : Element, initial : Boolean):
+	Element state
+	Element keys
+	Element sub
+	String key
+	String place
+
+	if (initial):
+		state = instantiate_node(model, "ReachabilityGraph/InitialState", name)
+	else:
+		state = instantiate_node(model, "ReachabilityGraph/State", name)
+	instantiate_attribute(model, state, "name", name)
+	instantiate_attribute(model, state, "error", False)
+
+	keys = dict_keys(dict_repr)
+
+	while (read_nr_out(keys) > 0):
+		key = set_pop(keys)
+		name = read_attribute(model, key, "name")
+		if (bool_not(dict_in(cache, name))):
+			dict_add_fast(cache, name, create_node())
+		sub = cache[name]
+		if (bool_not(dict_in(sub, dict_repr[key]))):
+			place = instantiate_node(model, "ReachabilityGraph/Place", "")
+			instantiate_attribute(model, place, "name", name)
+			instantiate_attribute(model, place, "tokens", dict_repr[key])
+			dict_add_fast(sub, dict_repr[key], place)
+		else:
+			place = sub[dict_repr[key]]
+		instantiate_link(model, "ReachabilityGraph/Contains", "", state, place)
+	return state!

+ 58 - 60
integration/code/reachabilitygraph_print.mvc

@@ -2,72 +2,70 @@ include "primitives.alh"
 include "modelling.alh"
 include "object_operations.alh"
 
-ReachabilityGraph_RAM reachabilitygraph_print {
-    Composite schedule {
-        {Contains} Success success {}
-        {Contains} Failure failure {}
-        {Contains} ForAll print_states {
-            LHS {
-                Pre_ReachabilityGraph/State {
-                    label = "0"
-                }
+Composite schedule {
+    {Contains} Success success {}
+    {Contains} Failure failure {}
+    {Contains} ForAll print_states {
+        LHS {
+            Pre_ReachabilityGraph/State {
+                label = "0"
             }
-            RHS {
-                Post_ReachabilityGraph/State {
-                    label = "0"
-                    action = $
-                        Void function action(model : Element, name : String, mapping : Element):
-                            Element dict_values
-                            Element all_values
-                            String place
-                            dict_values = create_node()
-                            all_values = allAssociationDestinations(model, name, "ReachabilityGraph/Contains")
-                            while (read_nr_out(all_values) > 0):
-                                place = set_pop(all_values)
-                                dict_add(dict_values, read_attribute(model, place, "name"), read_attribute(model, place, "tokens"))
-                            log((cast_v2s(read_attribute(model, name, "name")) + ": ") + dict_to_string(dict_values))
-                            output((cast_v2s(read_attribute(model, name, "name")) + ": ") + dict_to_string(dict_values))
-                            return!
-                        $
-                }
+        }
+        RHS {
+            Post_ReachabilityGraph/State {
+                label = "0"
+                action = $
+                    Void function action(model : Element, name : String, mapping : Element):
+                        Element dict_values
+                        Element all_values
+                        String place
+                        dict_values = create_node()
+                        all_values = allAssociationDestinations(model, name, "ReachabilityGraph/Contains")
+                        while (read_nr_out(all_values) > 0):
+                            place = set_pop(all_values)
+                            dict_add(dict_values, read_attribute(model, place, "name"), read_attribute(model, place, "tokens"))
+                        log((cast_v2s(read_attribute(model, name, "name")) + ": ") + dict_to_string(dict_values))
+                        output((cast_v2s(read_attribute(model, name, "name")) + ": ") + dict_to_string(dict_values))
+                        return!
+                    $
             }
         }
+    }
 
-        {Contains} ForAll print_transitions {
-            LHS {
-                Pre_ReachabilityGraph/State pre_s1 {
-                    label = "0"
-                }
-                Pre_ReachabilityGraph/State pre_s2 {
-                    label = "1"
-                }
-                Pre_ReachabilityGraph/Transition (pre_s1, pre_s2){
-                    label = "2"
-                }
+    {Contains} ForAll print_transitions {
+        LHS {
+            Pre_ReachabilityGraph/State pre_s1 {
+                label = "0"
+            }
+            Pre_ReachabilityGraph/State pre_s2 {
+                label = "1"
             }
-            RHS {
-                Post_ReachabilityGraph/State post_s1 {
-                    label = "0"
-                }
-                Post_ReachabilityGraph/State post_s2 {
-                    label = "1"
-                }
-                Post_ReachabilityGraph/Transition (post_s1, post_s2) {
-                    label = "2"
-                    action = $
-                        Void function action(model : Element, name : String, mapping : Element):
-                            log((((cast_v2s(read_attribute(model, mapping["0"], "name")) + " --[") + cast_v2s(read_attribute(model, name, "name"))) + "]--> ") + cast_v2s(read_attribute(model, mapping["1"], "name")))
-                            output((((cast_v2s(read_attribute(model, mapping["0"], "name")) + " --[") + cast_v2s(read_attribute(model, name, "name"))) + "]--> ") + cast_v2s(read_attribute(model, mapping["1"], "name")))
-                            return!
-                        $
-                }
+            Pre_ReachabilityGraph/Transition (pre_s1, pre_s2){
+                label = "2"
+            }
+        }
+        RHS {
+            Post_ReachabilityGraph/State post_s1 {
+                label = "0"
+            }
+            Post_ReachabilityGraph/State post_s2 {
+                label = "1"
+            }
+            Post_ReachabilityGraph/Transition (post_s1, post_s2) {
+                label = "2"
+                action = $
+                    Void function action(model : Element, name : String, mapping : Element):
+                        log((((cast_v2s(read_attribute(model, mapping["0"], "name")) + " --[") + cast_v2s(read_attribute(model, name, "name"))) + "]--> ") + cast_v2s(read_attribute(model, mapping["1"], "name")))
+                        output((((cast_v2s(read_attribute(model, mapping["0"], "name")) + " --[") + cast_v2s(read_attribute(model, name, "name"))) + "]--> ") + cast_v2s(read_attribute(model, mapping["1"], "name")))
+                        return!
+                    $
             }
         }
     }
-
-    Initial (schedule, print_states) {}
-    OnSuccess (print_states, print_transitions) {}
-    OnFailure (print_states, failure) {}
-    OnSuccess (print_transitions, success) {}
-    OnFailure (print_transitions, success) {}
 }
+
+Initial (schedule, print_states) {}
+OnSuccess (print_states, print_transitions) {}
+OnFailure (print_states, failure) {}
+OnSuccess (print_transitions, success) {}
+OnFailure (print_transitions, success) {}

+ 0 - 166
integration/code/several_petrinets.mvc

@@ -1,166 +0,0 @@
-import models/SimpleClassDiagrams as SCD
-include "primitives.alh"
-include "modelling.alh"
-
-SCD PetriNets{
-    SimpleAttribute Natural {
-        constraint =
-            $
-            String function constraint_Natural(model : Element, name : String):
-                Element self
-                self = model["model"][name]
-                if (is_physical_int(self)):
-                    if (integer_gte(self, 0)):
-                        return "OK"!
-                    else:
-                        return ("Natural does not have a positive or zero value at " + name)!
-                else:
-                    return ("Natural has no integer value at " + name)!
-            $
-    }
-
-    Class Place{
-        tokens : Natural
-    }
-    Class Transition{}
-    Association P2T (Place, Transition) {
-        weight : Natural
-    }
-    Association T2P (Transition, Place) {
-        weight : Natural
-    }
-}
-
-PetriNets valid_petrinet {
-    Place p1 {
-        tokens = 1
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T (p1, t1) {
-        weight = 1
-    }
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-PetriNets invalid_petrinet_1 {
-    Place p1 {
-        tokens = -1
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T (p1, t1) {
-        weight = 1
-    }
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-PetriNets invalid_petrinet_2 {
-    Place p1 {
-        tokens = 1
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T p2t(p1, t1) {
-        weight = -1
-    }
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-PetriNets invalid_petrinet_3 {
-    Place p1 {
-        tokens = 1
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T wrong_p2t (p1, p2) {
-        weight = 1
-    }
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-PetriNets invalid_petrinet_4 {
-    Place p1 {
-        tokens = 1
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T (p1, t1) {
-        weight = 1
-    }
-    T2P wrong_t2p(p1, p2) {
-        weight = 2
-    }
-}
-
-PetriNets invalid_petrinet_5 {
-    Place p1 {}
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T (p1, t1) {
-        weight = 1
-    }
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-PetriNets invalid_petrinet_6 {
-    Place p1 {
-        tokens = 1
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T p2t (p1, t1) {}
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-PetriNets invalid_petrinet_7 {
-    Place p1 {
-        tokens = "abc"
-    }
-    Place p2 {
-        tokens = 3
-    }
-    Transition t1 {}
-    P2T (p1, t1) {
-        weight = 1
-    }
-    T2P (t1, p2) {
-        weight = 2
-    }
-}
-
-export PetriNets to models/PetriNets
-export valid_petrinet to models/valid_petrinet
-export invalid_petrinet_1 to models/invalid_petrinet_1
-export invalid_petrinet_2 to models/invalid_petrinet_2
-export invalid_petrinet_3 to models/invalid_petrinet_3
-export invalid_petrinet_4 to models/invalid_petrinet_4
-export invalid_petrinet_5 to models/invalid_petrinet_5
-export invalid_petrinet_6 to models/invalid_petrinet_6
-export invalid_petrinet_7 to models/invalid_petrinet_7

+ 0 - 31
integration/code/simpleclassdiagrams.mvc

@@ -1,31 +0,0 @@
-import /formalisms/SimpleClassDiagrams as SCD
-
-SCD SimpleClassDiagrams{
-    SimpleAttribute Natural {}
-    SimpleAttribute String {}
-    SimpleAttribute Boolean {}
-
-    Class Element {}
-    Class Class{
-        lower_cardinality? : Natural
-        upper_cardinality? : Natural
-    }
-
-    Association Association (Element, Element){
-        source_lower_cardinality? : Natural
-        source_upper_cardinality? : Natural
-        target_lower_cardinality? : Natural
-        target_upper_cardinality? : Natural
-    }
-
-    Association Attribute (Element, AttributeValue) {
-        optional : Boolean
-        name : String
-    }
-
-    Class AttributeValue {}
-    Association Inheritance (Element, Element){}
-    Inheritance assoc_inh_class (Association, Class) {}
-    Inheritance class_inh_element (Class, Element) {}
-    Inheritance attributevalue_inh_element (AttributeValue, Element) {}
-}

+ 33 - 1
integration/test_mvc.py

@@ -266,7 +266,7 @@ class TestModelverseCore(unittest.TestCase):
                                 '"p2" --> 1',
                                 '"p3" --> 5'])
 
-    def test_process_model_trivial_pn(self):
+    def test_process_model_trivial_pn_bigmain(self):
         model_add("PetriNet", "SimpleClassDiagrams", open("integration/code/pn_design.mvc", "r").read())
         model_add("ReachabilityGraph", "SimpleClassDiagrams", open("integration/code/reachability_graph.mvc", "r").read())
         model_add("pn_reachability", "ProcessModel", open("integration/code/pm_pn_reachability.mvc", "r").read())
@@ -298,6 +298,38 @@ class TestModelverseCore(unittest.TestCase):
                            '"1": {"p1": 0, }',
                            '"0" --["t1"]--> "1"'])
 
+    def test_process_model_trivial_pn_subfunction(self):
+        model_add("PetriNet", "SimpleClassDiagrams", open("integration/code/pn_design.mvc", "r").read())
+        model_add("ReachabilityGraph", "SimpleClassDiagrams", open("integration/code/reachability_graph.mvc", "r").read())
+        model_add("pn_reachability", "ProcessModel", open("integration/code/pm_pn_reachability.mvc", "r").read())
+        transformation_add_MT_language(["PetriNet"], "PetriNet_RAM")
+        transformation_add_MT_language(["ReachabilityGraph"], "ReachabilityGraph_RAM")
+        transformation_add_MT("PetriNet_RAM", [], ["PetriNet"], "initialize_PN", open("integration/code/initialize_PN.mvc", "r").read())
+        transformation_add_MANUAL(["PetriNet"], ["PetriNet"], "refine_PN")
+        transformation_add_AL(["PetriNet"], ["ReachabilityGraph"], "reachability", open("integration/code/reachability_subfunction.alc", "r").read())
+        transformation_add_MT("ReachabilityGraph_RAM", ["ReachabilityGraph"], [], "reachability_print", open("integration/code/reachabilitygraph_print.mvc", 'r').read())
+
+        def callback_refine_PN():
+            p1 = instantiate(None, "PetriNet/Place")
+            attr_assign(None, p1, "name", "p1")
+            attr_assign(None, p1, "tokens", 1)
+
+            t1 = instantiate(None, "PetriNet/Transition")
+            attr_assign(None, t1, "name", "t1")
+
+            p2t = instantiate(None, "PetriNet/P2T", (p1, t1))
+            attr_assign(None, p2t, "weight", 1)
+
+        log = set([])
+        def callback_print(value):
+            log.add(value)
+
+        process_execute("pn_reachability", "my_", {"refine_PN": callback_refine_PN, "reachability_print": callback_print})
+
+        assert log == set(['"0": {"p1": 1, }',
+                           '"1": {"p1": 0, }',
+                           '"0" --["t1"]--> "1"'])
+
     def test_render(self):
         model_add("CausalBlockDiagrams", "SimpleClassDiagrams", open("integration/code/cbd_design.mvc", 'r').read())
         model_add("MM_rendered_graphical", "SimpleClassDiagrams", open("models/MM_rendered_graphical.mvc", 'r').read())

+ 1 - 5
interface/HUTN/grammars/modelling.g

@@ -1,12 +1,8 @@
 grammar{
-    start: (import | export | include_files | model | NEWLINE)+;
+    start: (include_files | model_element | NEWLINE)*;
 
-    import: IMPORT MV_URL AS MODEL_ID;
-    export: EXPORT MODEL_ID TO MV_URL;
     include_files: INCLUDE STRVALUE NEWLINE;
 
-    model: MODEL_ID MODEL_ID NEWLINE? LCURLY NEWLINE? (model_element)* RCURLY;
-
     model_element: MODEL_ID MODEL_ID? inheritance? (LPAR MODEL_ID COMMA MODEL_ID RPAR)? NEWLINE? LCURLY NEWLINE? (model_attribute)* RCURLY NEWLINE?;
 
     inheritance: COLON MODEL_ID (COMMA MODEL_ID)*;

+ 56 - 0
interface/HUTN/grammars/modelling_bootstrap.g

@@ -0,0 +1,56 @@
+grammar{
+    start: (import | export | include_files | model | NEWLINE)*;
+
+    import: IMPORT MV_URL AS MODEL_ID;
+    export: EXPORT MODEL_ID TO MV_URL;
+    include_files: INCLUDE STRVALUE NEWLINE;
+
+    model: MODEL_ID MODEL_ID NEWLINE? LCURLY NEWLINE? (model_element)* RCURLY;
+
+    model_element: MODEL_ID MODEL_ID? inheritance? (LPAR MODEL_ID COMMA MODEL_ID RPAR)? NEWLINE? LCURLY NEWLINE? (model_attribute)* RCURLY NEWLINE?;
+
+    inheritance: COLON MODEL_ID (COMMA MODEL_ID)*;
+
+    model_attribute : ((LCURLY MODEL_ID RCURLY)? model_element)
+                    | (MODEL_ID OPTIONAL? COLON MODEL_ID (LCURLY NEWLINE? model_attr_instance* RCURLY)? NEWLINE?)
+                    | (model_attr_instance);
+
+    model_attr_instance: (MODEL_ID ASSIGN value NEWLINE?)
+                       | (MODEL_ID ASSIGN NEWLINE? DOLLAR ANYTHING_EXCEPT_DOLLAR DOLLAR NEWLINE?);
+
+    value
+        : DEC_NUMBER
+        | FLOAT_NUMBER
+        | TRUE
+        | FALSE
+        | STRVALUE;
+
+    tokens{
+        IMPORT: 'import';
+        OPTIONAL: '\?';
+        AS: 'as';
+        MODEL_ID: '[a-zA-Z_][a-zA-Z_0-9/]*';
+        MV_URL: '[a-zA-Z_0-9/]*';
+        LCURLY: '{';
+        RCURLY: '}';
+        NEWLINE: '(\r?\n)+';
+        DEC_NUMBER: '[+-]?(0|[1-9]\d*[lL]?)';
+        FLOAT_NUMBER: '[+-]?((\d+\.\d*|\.\d+)([eE][-+]?\d+)?|\d+[eE][-+]?\d+)';
+        STRVALUE: 'u?r?("(?!"").*?(?<!\\)(\\\\)*?"|\'(?!\'\').*?(?<!\\)(\\\\)*?\')';
+        TRUE: 'True';
+        FALSE: 'False';
+        ASSIGN: '=';
+        DOLLAR: '\$';
+        WS: '[ ]+' @Impl;
+        TAB: '[\t]+' @Impl;
+        COLON : ':';
+        LPAR: '\(';
+        RPAR: '\)';
+        COMMA: ',';
+        EXPORT: 'export';
+        TO: 'to';
+        ANYTHING_EXCEPT_DOLLAR: '[^$]*';
+        INCLUDE: 'include';
+        EXCLAMATION: '!';
+    }
+}

+ 2 - 8
interface/HUTN/hutn_compiler/bootstrap_visitor.py

@@ -13,8 +13,6 @@ class BootstrapVisitor(PrimitivesVisitor):
         else:
             self.prepend_name = "auto"
 
-        self.object_symbols = {}
-
     def rename(self, name):
         if name == "initial_IP":
             return "%s_%s" % (self.prepend_name, name)
@@ -66,17 +64,16 @@ class BootstrapVisitor(PrimitivesVisitor):
                 output.append("Edge _%s(_%s, _%s)\n" % (name, source, target))
         return ''.join(output)
 
+    """
     def visit_definition(self, tree):
         for a in tree.get_children("ID"):
             name = a.get_tail()[0]
-            self.object_symbols[name] = True
             return PrimitivesVisitor.visit_definition(self, tree)
 
     def visit_vardecl(self, tree):
         if len(tree.get_tail()) > 2:
             for a in tree.get_children("ID"):
                 name = a.get_tail()[0]
-                self.object_symbols.setdefault(name, False)
                 return PrimitivesVisitor.visit_vardecl(self, tree)
         else:
             return PrimitivesVisitor.visit_vardecl(self, tree)
@@ -85,8 +82,5 @@ class BootstrapVisitor(PrimitivesVisitor):
         for a in tree.get_children("func_name"):
             for b in a.get_children("ID"):
                 name = b.get_tail()[0]
-                if tree.get_children("func_body") or tree.get_children("ASSIGN"):
-                    self.object_symbols[name] = True
-                else:
-                    self.object_symbols.setdefault(name, False)
                 return PrimitivesVisitor.visit_funcdecl(self, tree)
+    """

+ 1 - 12
interface/HUTN/hutn_compiler/compiler.py

@@ -141,38 +141,27 @@ def do_compile(inputfile, grammarfile, visitors=[], include_paths = []):
     if visitors:
         return visitors[-1].dump()
 
-def main(input_file, grammar_file, mode, args=[], symbols=None):
+def main(input_file, grammar_file, mode, args=[]):
     from prettyprint_visitor import PrettyPrintVisitor
     from prettyprint_visitor import PrintVisitor
     from semantics_visitor import SemanticsVisitor
     from bootstrap_visitor import BootstrapVisitor
-    from primitives_visitor import PrimitivesVisitor
-    from primitives_object_visitor import PrimitivesObjectVisitor
     from constructors_visitor import ConstructorsVisitor
-    from constructors_object_visitor import ConstructorsObjectVisitor
     from model_visitor import ModelVisitor
     from model_bootstrap_visitor import ModelBootstrapVisitor
-    from model_object_visitor import ModelObjectVisitor
 
     modes = {
         "N" : [],
         "P" : [PrintVisitor],
         "PP" : [PrettyPrintVisitor],
-        "S" : [SemanticsVisitor],
-        "PS" : [SemanticsVisitor, PrimitivesVisitor],
-        "PO" : [SemanticsVisitor, PrimitivesObjectVisitor],
         "BS" : [SemanticsVisitor, BootstrapVisitor],
         "CS" : [SemanticsVisitor, ConstructorsVisitor],
-        "CO" : [SemanticsVisitor, ConstructorsObjectVisitor],
         "M" : [ModelVisitor],
         "MB" : [ModelBootstrapVisitor],
-        "MO" : [ModelObjectVisitor],
     }
     try:
         visitors = [v(args) for v in modes[mode]]
         result = do_compile(input_file, grammar_file, visitors)
-        if symbols is not None and mode == "BS":
-            symbols.update(visitors[-1].object_symbols)
     except CachedException:
         return True
     return result

+ 0 - 89
interface/HUTN/hutn_compiler/constructors_object_visitor.py

@@ -1,89 +0,0 @@
-import sys
-sys.path.append("scripts")
-
-from constructors_visitor import ConstructorsVisitor
-from cached_exception import CachedException
-
-import urllib
-import urllib2
-import json
-
-timeout = 100
-
-class ConstructorsObjectVisitor(ConstructorsVisitor):
-    def __init__(self, args):
-        ConstructorsVisitor.__init__(self, args)
-
-        self.taskname = args[0]
-        self.obj_file = args[1]
-        self.real_file = args[2]
-        self.address = args[3]
-
-        self.object_symbols = {}
-
-        with open(self.real_file, 'r') as f:
-            import hashlib
-            md5 = hashlib.md5()
-            md5.update(f.read())
-        self.hash_file = md5.hexdigest()
-
-        # Create task
-        urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "set_input", "value": '"%s"' % self.taskname, "taskname": "task_manager"}))).read()
-
-        simple_filename = self.real_file.rsplit("/")[-1]
-        print("[COMPILE] %s" % simple_filename)
-
-    def dump(self):
-        v = ConstructorsVisitor.dump(self)
-
-        def flush_data(data):
-            if data:
-                urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "taskname": self.taskname})), timeout=timeout).read()
-            return []
-
-        # Set up interface
-        flush_data([3, "upload", self.obj_file, self.hash_file, True])
-        flush_data(v)
-
-        # Upload symbol table
-        data = []
-        for e, v in self.object_symbols.iteritems():
-            data.extend([True, e, v])
-        # Finish the symbol table
-        data.append(False)
-
-        urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "taskname": self.taskname}))).read()
-
-        # Wait for kernel to signal that it finished
-        urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "set_input", "value": '2', "taskname": self.taskname}))).read()
-        v = urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "get_output", "taskname": self.taskname}))).read()
-        v = json.loads(v)
-        if v == "DONE":
-            return True
-        else:
-            return False
-
-    def visit_definition(self, tree):
-        for a in tree.get_children("ID"):
-            name = a.get_tail()[0]
-            self.object_symbols[name] = True
-            return ConstructorsVisitor.visit_definition(self, tree)
-
-    def visit_vardecl(self, tree):
-        if len(tree.get_tail()) > 2:
-            for a in tree.get_children("ID"):
-                name = a.get_tail()[0]
-                self.object_symbols.setdefault(name, False)
-                return ConstructorsVisitor.visit_vardecl(self, tree)
-        else:
-            return ConstructorsVisitor.visit_vardecl(self, tree)
-
-    def visit_funcdecl(self, tree):
-        for a in tree.get_children("func_name"):
-            for b in a.get_children("ID"):
-                name = b.get_tail()[0]
-                if tree.get_children("func_body") or tree.get_children("ASSIGN"):
-                    self.object_symbols[name] = True
-                else:
-                    self.object_symbols.setdefault(name, False)
-                return ConstructorsVisitor.visit_funcdecl(self, tree)

+ 0 - 35
interface/HUTN/hutn_compiler/linker.py

@@ -1,35 +0,0 @@
-import sys
-import urllib
-import urllib2
-import json
-
-sys.path.append("scripts")
-
-def link(address, taskname, objects):
-    # Read out all symbol tables that are to be linked
-    definers = {}
-    tasks = {}
-    def flush_data(data):
-        if data:
-            urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "taskname": taskname})), timeout=10).read()
-        return []
-    flush_data([3, "link_and_load"] + objects + ["", "main"])
-
-    v = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname}))).read()
-    v = json.loads(v)
-    if "OK" not in v:
-        print(v)
-        raise Exception("Linking error")
-
-if __name__ == "__main__":
-    if len(sys.argv) == 1:
-        print("No taskname defined")
-    else:
-        address = sys.argv[1]
-        taskname = sys.argv[2]
-        objects = set(sys.argv[3:])
-
-        if objects:
-            link(address, taskname, objects)
-        else:
-            print("No files to link defined")

+ 0 - 32
interface/HUTN/hutn_compiler/model_object_visitor.py

@@ -1,32 +0,0 @@
-from model_visitor import ModelVisitor
-from compiler import main as do_compile
-import os
-import urllib2
-import urllib
-import json
-
-def empty(s):
-    return None
-
-class ModelObjectVisitor(ModelVisitor):
-    def __init__(self, args):
-        ModelVisitor.__init__(self, args)
-        self.taskname = args[0]
-        self.obj_file = args[1]
-        self.real_file = args[2]
-        self.address = args[3]
-
-    def dump(self):
-        v = ModelVisitor.dump(self)
-        data = [4] + v + ["exit"]
-
-        # Wait for kernel to signal that it finished
-        data.append(2)
-
-        urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "taskname": self.taskname}))).read()
-        v = urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "get_output", "taskname": self.taskname}))).read()
-        v = json.loads(v)
-        if v == "DONE":
-            return True
-        else:
-            return False

+ 9 - 28
interface/HUTN/hutn_compiler/model_visitor.py

@@ -11,7 +11,6 @@ class ModelVisitor(Visitor):
         self.constructors = []
         self.free_id = 0
         self.names = set()
-        self.current_model = None
         self.current_element = []
         self.includes = []
 
@@ -31,26 +30,6 @@ class ModelVisitor(Visitor):
     def visit_include_files(self, tree):
         self.includes.append('include %s' % tree.get_children("STRVALUE")[0].get_text())
 
-    def visit_import(self, tree):
-        url = tree.get_children("MV_URL")[0]
-        target = tree.get_children("MODEL_ID")[0]
-        self.constructors.extend(["import_node", url.get_text(), target.get_text()])
-
-    def visit_export(self, tree):
-        url = tree.get_children("MV_URL")[0]
-        target = tree.get_children("MODEL_ID")[0]
-        self.constructors.extend(["export_node", target.get_text(), url.get_text()])
-
-    def visit_model(self, tree):
-        children = tree.get_children("MODEL_ID")
-        model_type = children[0].get_text()
-        model_name = children[-1].get_text()
-        self.constructors.extend(["instantiate_model", model_type, model_name])
-        self.current_model = model_name
-        self.names = set()
-        for element in tree.get_children("model_element"):
-            self.visit(element)
-
     def visit_model_element(self, tree):
         children = tree.get_children("MODEL_ID")
         element_type = children[0].get_text()
@@ -72,9 +51,9 @@ class ModelVisitor(Visitor):
             if target_name not in self.names:
                 raise Exception("Target of link %s unknown: %s" % (element_name, target_name))
 
-            self.constructors.extend(["instantiate_link", self.current_model, element_type, element_name, source_name, target_name])
+            self.constructors.extend(["instantiate_link", element_type, element_name, source_name, target_name])
         else:
-            self.constructors.extend(["instantiate_node", self.current_model, element_type, element_name])
+            self.constructors.extend(["instantiate_node", element_type, element_name])
 
         self.names.add(element_name)
         self.current_element.append(element_name)
@@ -95,7 +74,7 @@ class ModelVisitor(Visitor):
             if superclass not in self.names:
                 raise Exception("Superclass %s is undefined" % superclass)
 
-            self.constructors.extend(["instantiate_link", self.current_model, "Inheritance", "%s_inherits_from_%s" % (self.current_element[-1], superclass), self.current_element[-1], superclass])
+            self.constructors.extend(["instantiate_link", "Inheritance", "%s_inherits_from_%s" % (self.current_element[-1], superclass), self.current_element[-1], superclass])
             self.names.add("%s_inherits_from_%s" % (self.current_element[-1], superclass))
 
     def visit_model_attribute(self, tree):
@@ -108,7 +87,9 @@ class ModelVisitor(Visitor):
             attr_name = children[0].get_text()
             attr_optional = len(tree.get_children("OPTIONAL")) > 0
             attr_type = children[1].get_text()
-            self.constructors.extend(["model_define_attribute", self.current_model, self.current_element[-1], attr_name, attr_optional, attr_type])
+            if attr_type not in self.names:
+                raise Exception("Unknown Attribute type!")
+            self.constructors.extend(["model_define_attribute", self.current_element[-1], attr_name, attr_optional, attr_type])
             full_attribute_name = self.current_element[-1] + "_" + attr_name
 
             if is_assign:
@@ -127,7 +108,7 @@ class ModelVisitor(Visitor):
             else:
                 contains_link = ""
             entry = self.visit(tree.get_children("model_element")[0])
-            self.constructors.extend(["instantiate_link", self.current_model, contains_link, "__%s" % self.free_id, self.current_element[-1], entry])
+            self.constructors.extend(["instantiate_link", contains_link, "__%s" % self.free_id, self.current_element[-1], entry])
             self.names.add("__%s" % self.free_id)
             self.free_id += 1
 
@@ -165,8 +146,8 @@ class ModelVisitor(Visitor):
                 attr_value = float(attr_value.get_text())
             else:
                 raise Exception(attr_value.head)
-            self.constructors.extend(["instantiate_attribute", self.current_model, self.current_element[-1], attr_name, attr_value])
+            self.constructors.extend(["instantiate_attribute", self.current_element[-1], attr_name, attr_value])
         elif tree.get_children("DOLLAR"):
             # Coded attribute
-            self.constructors.extend(["instantiate_attribute_code", self.current_model, self.current_element[-1], attr_name])
+            self.constructors.extend(["instantiate_attribute_code", self.current_element[-1], attr_name])
             self.constructors.extend(constructors_compile(tree.get_children("ANYTHING_EXCEPT_DOLLAR")[0].get_text()))

+ 0 - 83
interface/HUTN/hutn_compiler/primitives_object_visitor.py

@@ -1,83 +0,0 @@
-import string
-from primitives_visitor import PrimitivesVisitor
-from cached_exception import CachedException
-
-import urllib
-import urllib2
-import json
-
-class PrimitivesObjectVisitor(PrimitivesVisitor):
-    def __init__(self, args):
-        PrimitivesVisitor.__init__(self, args)
-
-        self.taskname = args[0]
-        self.obj_file = args[1]
-        self.real_file = args[2]
-        self.address = args[3]
-
-        self.object_symbols = {}
-
-        with open(self.real_file, 'r') as f:
-            import hashlib
-            md5 = hashlib.md5()
-            md5.update(f.read())
-        self.hash_file = md5.hexdigest()
-
-        # Create task
-        urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "set_input", "value": '"%s"' % self.taskname, "taskname": "task_manager"}))).read()
-
-        simple_filename = self.real_file.rsplit("/")[-1]
-        print("[COMPILE] %s" % simple_filename)
-
-    def dump(self):
-        v = PrimitivesVisitor.dump(self)
-        data = []
-
-        # Set up interface
-        data = [3, "upload", self.obj_file, self.hash_file, False]
-
-        # Start uploading the code
-        data.append(v)
-
-        # Upload symbol table
-        for e, v in self.object_symbols.iteritems():
-            data.extend([True, e, v])
-
-        # Finish the symbol table
-        data.append(False)
-
-        # Wait for kernel to signal that it finished
-        data.append(2)
-
-        urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "taskname": self.taskname}))).read()
-        v = urllib2.urlopen(urllib2.Request(self.address, urllib.urlencode({"op": "get_output", "taskname": self.taskname}))).read()
-        v = json.loads(v)
-        if v == "DONE":
-            return True
-        else:
-            return False
-
-    def visit_definition(self, tree):
-        for a in tree.get_children("ID"):
-            name = a.get_tail()[0]
-            self.object_symbols[name] = True
-            return PrimitivesVisitor.visit_definition(self, tree)
-
-    def visit_vardecl(self, tree):
-        if len(tree.get_tail()) > 2:
-            for a in tree.get_children("ID"):
-                name = a.get_tail()[0]
-                self.object_symbols.setdefault(name, False)
-                return PrimitivesVisitor.visit_vardecl(self, tree)
-        else:
-            return PrimitivesVisitor.visit_vardecl(self, tree)
-
-    def visit_funcdecl(self, tree):
-        for a in tree.get_children("func_name"):
-            for b in a.get_children("ID"):
-                name = b.get_tail()[0]
-                if tree.get_children("func_body") or tree.get_children("ASSIGN"):
-                    self.object_symbols[name] = True
-                else:
-                    self.object_symbols.setdefault(name, False)
-                return PrimitivesVisitor.visit_funcdecl(self, tree)

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

@@ -1,3 +1 @@
-Action function construct_top()
-Action function construct_unknown()
 Action function construct_function()

+ 2 - 2
interface/HUTN/test/constructor_compilation_action_language/code/include.al

@@ -1,5 +1,5 @@
-include "test/graph_compilation_action_language/code/integer.al"
-include "test/graph_compilation_action_language/code/float.al"
+include "test/constructor_compilation_action_language/code/integer.al"
+include "test/constructor_compilation_action_language/code/float.al"
 
 Void function main():
 	integer_addition(1, 2)

interface/HUTN/test/grammar_action_language/code/accumulate.al → interface/HUTN/test/grammar_action_language/code/accumulate.alc


interface/HUTN/test/grammar_action_language/code/action.al → interface/HUTN/test/grammar_action_language/code/action.alc


interface/HUTN/test/grammar_action_language/code/assign.al → interface/HUTN/test/grammar_action_language/code/assign.alc


interface/HUTN/test/grammar_action_language/code/assign_to_constant.al → interface/HUTN/test/grammar_action_language/code/assign_to_constant.alc


interface/HUTN/test/grammar_action_language/code/assign_to_func_result.al → interface/HUTN/test/grammar_action_language/code/assign_to_func_result.alc


interface/HUTN/test/grammar_action_language/code/assign_to_statement.al → interface/HUTN/test/grammar_action_language/code/assign_to_statement.alc


interface/HUTN/test/grammar_action_language/code/dictionary_selection.al → interface/HUTN/test/grammar_action_language/code/dictionary_selection.alc


interface/HUTN/test/grammar_action_language/code/empty.al → interface/HUTN/test/grammar_action_language/code/empty.alc


interface/HUTN/test/grammar_action_language/code/fibonacci.al → interface/HUTN/test/grammar_action_language/code/fibonacci.alc


interface/HUTN/test/grammar_action_language/code/full_empty.al → interface/HUTN/test/grammar_action_language/code/full_empty.alc


interface/HUTN/test/grammar_action_language/code/funcdef_empty_body.al → interface/HUTN/test/grammar_action_language/code/funcdef_empty_body.alc


interface/HUTN/test/grammar_action_language/code/global.al → interface/HUTN/test/grammar_action_language/code/global.alc


interface/HUTN/test/grammar_action_language/code/if.al → interface/HUTN/test/grammar_action_language/code/if.alc


interface/HUTN/test/grammar_action_language/code/if_empty_body.al → interface/HUTN/test/grammar_action_language/code/if_empty_body.alc


interface/HUTN/test/grammar_action_language/code/if_empty_else.al → interface/HUTN/test/grammar_action_language/code/if_empty_else.alc


interface/HUTN/test/grammar_action_language/code/if_no_condition.al → interface/HUTN/test/grammar_action_language/code/if_no_condition.alc


interface/HUTN/test/grammar_action_language/code/if_only_else.al → interface/HUTN/test/grammar_action_language/code/if_only_else.alc


+ 0 - 4
interface/HUTN/test/grammar_action_language/code/include.al

@@ -1,4 +0,0 @@
-include "test/grammar_action_language/code/primitives.al"
-
-Void function main():
-	integer_addition(1, 2)

+ 4 - 0
interface/HUTN/test/grammar_action_language/code/include.alc

@@ -0,0 +1,4 @@
+include "test/grammar_action_language/code/primitives.alc"
+
+Void function main():
+	integer_addition(1, 2)

interface/HUTN/test/grammar_action_language/code/include_late.al → interface/HUTN/test/grammar_action_language/code/include_late.alc


+ 9 - 0
interface/HUTN/test/grammar_action_language/code/nested.alc

@@ -0,0 +1,9 @@
+Void function run_1():
+	Integer function fibonacci(n : Integer):
+		if (n > 2):
+			return (fibonacci(n-1) + fibonacci(n-2))!
+		else:
+			return 1!
+
+	log(fibonacci(5))
+	return!

interface/HUTN/test/grammar_action_language/code/primitives.al → interface/HUTN/test/grammar_action_language/code/primitives.alc


interface/HUTN/test/grammar_action_language/code/return_in_assign.al → interface/HUTN/test/grammar_action_language/code/return_in_assign.alc


interface/HUTN/test/grammar_action_language/code/types.al → interface/HUTN/test/grammar_action_language/code/types.alc


interface/HUTN/test/grammar_action_language/code/vardecl.al → interface/HUTN/test/grammar_action_language/code/vardecl.alc


interface/HUTN/test/grammar_action_language/code/while.al → interface/HUTN/test/grammar_action_language/code/while.alc


interface/HUTN/test/grammar_action_language/code/while_empty_body.al → interface/HUTN/test/grammar_action_language/code/while_empty_body.alc


interface/HUTN/test/grammar_action_language/code/while_no_condition.al → interface/HUTN/test/grammar_action_language/code/while_no_condition.alc


+ 2 - 0
interface/HUTN/test/grammar_action_language/test_invalids.py

@@ -50,3 +50,5 @@ class TestValids(unittest.TestCase):
     def test_include_late(self):
         self.assertTrue(parse_file("include_late.al"))
 
+    def test_nested(self):
+        self.assertTrue(parse_file("nested.alc"))

+ 13 - 16
interface/HUTN/test/grammar_action_language/test_valids.py

@@ -4,42 +4,39 @@ import util
 from hutn_compiler.compiler import main
 
 def parse_file(filename):
-    try:
-        main(util.get_code_path(filename), "grammars/actionlanguage.g", "N", [])
-        return True
-    except:
-        return False
+    main(util.get_code_path(filename), "grammars/actionlanguage.g", "N", [])
+    return True
 
 class TestValids(unittest.TestCase):
     def test_empty(self):
-        self.assertTrue(parse_file("empty.al"))
+        self.assertTrue(parse_file("empty.alc"))
 
     def test_assign(self):
-        self.assertTrue(parse_file("assign.al"))
+        self.assertTrue(parse_file("assign.alc"))
 
     def test_variable_declare(self):
-        self.assertTrue(parse_file("vardecl.al"))
+        self.assertTrue(parse_file("vardecl.alc"))
 
     def test_accumulate(self):
-        self.assertTrue(parse_file("accumulate.al"))
+        self.assertTrue(parse_file("accumulate.alc"))
 
     def test_fibonacci(self):
-        self.assertTrue(parse_file("fibonacci.al"))
+        self.assertTrue(parse_file("fibonacci.alc"))
 
     def test_while(self):
-        self.assertTrue(parse_file("while.al"))
+        self.assertTrue(parse_file("while.alc"))
 
     def test_if(self):
-        self.assertTrue(parse_file("if.al"))
+        self.assertTrue(parse_file("if.alc"))
 
     def test_action(self):
-        self.assertTrue(parse_file("action.al"))
+        self.assertTrue(parse_file("action.alc"))
 
     def test_type(self):
-        self.assertTrue(parse_file("types.al"))
+        self.assertTrue(parse_file("types.alc"))
 
     def test_global(self):
-        self.assertTrue(parse_file("global.al"))
+        self.assertTrue(parse_file("global.alc"))
 
     def test_include(self):
-        self.assertTrue(parse_file("include.al"))
+        self.assertTrue(parse_file("include.alc"))

+ 0 - 0
interface/HUTN/test/graph_compilation_action_language/__init__.py


+ 0 - 7
interface/HUTN/test/graph_compilation_action_language/code/action.al

@@ -1,7 +0,0 @@
-Void function test():
-	Action a
-	a = !if
-	a = !while
-	a = !assign
-	a = !global
-	a = !call

+ 0 - 3
interface/HUTN/test/graph_compilation_action_language/code/assign.al

@@ -1,3 +0,0 @@
-Void function test():
-	Integer a
-	a = 1

+ 0 - 2
interface/HUTN/test/graph_compilation_action_language/code/assign_invalid.al

@@ -1,2 +0,0 @@
-Integer a
-a = 1.0

+ 0 - 9
interface/HUTN/test/graph_compilation_action_language/code/dict_access.al

@@ -1,9 +0,0 @@
-Element function dict_read(a : Element, b : Element)
-Integer function integer_addition(a : Integer, b : Integer)
-
-Void function my_func():
-	Element d
-	Integer a
-	a = d["a"]["b"]["c"]
-	a = d[a]
-	a = integer_addition(d[123]["e"], d[111])

+ 0 - 2
interface/HUTN/test/graph_compilation_action_language/code/dictionary.al

@@ -1,2 +0,0 @@
-Element a
-a = {1: 2, "abc": 5, 1: {5: "def"}, True: False}

+ 0 - 15
interface/HUTN/test/graph_compilation_action_language/code/factorial.al

@@ -1,15 +0,0 @@
-Element integer_multiplication = ?primitives/integer_multiplication
-Element integer_lte = ?primitives/integer_lte
-Element integer_subtraction = ?primitives/integer_subtraction
-
-include "io.alh"
-
-Integer function factorial(n : Integer):
-	if(integer_lte(n, 1)):
-		return 1!
-	else:
-		return integer_multiplication(n, factorial(integer_subtraction(n, 1)))!
-
-Void function main():
-	while(True):
-		output(factorial(input()))

+ 0 - 15
interface/HUTN/test/graph_compilation_action_language/code/fibonacci.al

@@ -1,15 +0,0 @@
-Element integer_addition = ?primitives/integer_addition
-Element integer_lte = ?primitives/integer_lte
-Element integer_subtraction = ?primitives/integer_subtraction
-
-include "io.alh"
-
-Integer function fib(param : Integer):
-	if (integer_lte(param, 2)):
-		return 1!
-	else:
-		return integer_addition(fib(integer_subtraction(param, 1)), fib(integer_subtraction(param, 2)))!
-
-Void function main():
-	while(True):
-		output(fib(input()))

+ 0 - 25
interface/HUTN/test/graph_compilation_action_language/code/fibonacci_smart.al

@@ -1,25 +0,0 @@
-Element integer_addition = ?primitives/integer_addition
-Element integer_gt = ?primitives/integer_gt
-Element list_len = ?primitives/list_len
-Element list_append = ?primitives/list_append
-Element integer_subtraction = ?primitives/integer_subtraction
-Element dict_read = ?primitives/dict_read
-Element create_node = ?primitives/create_node
-
-Element numbers = ?
-
-include "io.alh"
-
-Integer function fib(param : Integer):
-	Integer new
-	while (integer_gt(param, list_len(numbers))):
-		new = list_len(numbers)
-		list_append(numbers, integer_addition(dict_read(numbers, integer_subtraction(new, 2)), dict_read(numbers, integer_subtraction(new, 1))))
-	return dict_read(numbers, integer_subtraction(param, 1))!
-
-Void function main():
-	numbers = create_node()
-	list_append(numbers, 1)
-	list_append(numbers, 1)
-	while(True):
-		output(fib(input()))

+ 0 - 0
interface/HUTN/test/graph_compilation_action_language/code/float.al


Неке датотеке нису приказане због велике количине промена