Sfoglia il codice sorgente

Changed some code to "break" and "continue", but code massively fails

Yentl Van Tendeloo 8 anni fa
parent
commit
64acf261ac

+ 2 - 2
bootstrap/constructors.alc

@@ -18,7 +18,7 @@ Action function construct_top():
 		elif (command == "mutable_funcdef"):
 			return construct_top_funcdef(True)!
 		else:
-			log("ERROR: did not understand command " + cast_e2s(command))
+			log("ERROR (1): did not understand command " + cast_e2s(command))
 
 Action function construct_global():
 	Action this_element
@@ -155,7 +155,7 @@ Action function construct_unknown():
 		construct_model()
 		return construct_unknown()!
 	else:
-		log("ERROR: did not understand command " + cast_e2s(elem))
+		log("ERROR (2): did not understand command " + cast_e2s(elem))
 
 Action function construct_if():
 	Action this_element

+ 2 - 1
bootstrap/transform.alc

@@ -176,12 +176,13 @@ Element function full_match(host_model : Element, schedule_model : Element, curr
 		mapping = set_pop(mappings)
 		i = 0
 		allowed = True
-		while (bool_and(i < read_nr_out(NACs), allowed)):
+		while (i < read_nr_out(NACs)):
 			NAC = read_edge_dst(read_out(NACs, i))
 			result = match(host_model, schedule_model, NAC, mapping)
 			if (read_nr_out(result) > 0):
 				// NAC could be matched, and therefore is not allowed
 				allowed = False
+				break!
 			i = i + 1
 		
 		if (allowed):

+ 12 - 18
core/core_algorithm.alc

@@ -58,11 +58,9 @@ Void function main():
 	instantiate_attribute(core, admin_user, "name", input())
 	instantiate_attribute(core, admin_user, "admin", True)
 
-	Boolean ct
 	String password
 
-	ct = True
-	while (ct):
+	while (True):
 		output("Desired password for admin user?")
 		password = hash(input())
 
@@ -70,7 +68,8 @@ Void function main():
 		if (password == hash(input())):
 			output("Passwords match!")
 			instantiate_attribute(core, admin_user, "password", password)
-			ct = False
+			log("BREAK")
+			break!
 		else:
 			output("Not the same password, please try again!")
 
@@ -230,10 +229,7 @@ Element function user_function():
 		instantiate_attribute(core, user_id, "name", username)
 		instantiate_attribute(core, user_id, "admin", False)
 
-		Boolean ct
-		ct = True
-
-		while (ct):
+		while (True):
 			output("This is a new user: please give password!")
 			password = hash(input())
 
@@ -242,7 +238,7 @@ Element function user_function():
 				output("Passwords match!")
 				output("User created")
 				instantiate_attribute(core, user_id, "password", password)
-				ct = False
+				break!
 			else:
 				output("Not the same password, please try again!")
 
@@ -325,15 +321,12 @@ Void function model_overwrite(model : Element, model_id : String):
 	return!
 
 Void function user_function_skip_init(user_id : String):
-	Boolean do_continue
 	String cmd
 
-	do_continue = True
-
 	output("Welcome to the Model Management Interface v2.0!")
 	output("Use the 'help' command for a list of possible commands")
 
-	while (do_continue):
+	while (True):
 		output("Ready for command...")
 		cmd = input()
 		if (cmd == "help"):
@@ -910,10 +903,12 @@ Void function user_function_skip_init(user_id : String):
 					i = 0
 					if (string_len(permissions) != 3):
 						fail = True
-					while (bool_and(bool_not(fail), i < 3)):
+
+					while (i < 3):
 						permission = cast_s2i(string_get(permissions, i))
 						if (bool_or(permission < 0, permission > 2)):
 							fail = True
+							break!
 						i = i + 1
 
 					if (bool_not(fail)):
@@ -1176,17 +1171,16 @@ Void function user_function_skip_init(user_id : String):
 		elif (cmd == "self-destruct"):
 			// Delete user from Core Formalism
 			model_delete_element(core, user_id)
-			do_continue = False
+			return !
 
 		elif (cmd == "exit"):
 			// Exit by actually removing the user and decoupling it from all of its models
 			// Restarting with the same user name will NOT grant you access to anything of the previous user with that same name
 			// as the current user will have been deleted
-			do_continue = False
+			return !
 
 		else:
 			output("Unknown command: " + cmd)
 
-	output("Goodbye!")
-
+	// We never get here!
 	return !

+ 3 - 0
integration/test_mvc.py

@@ -24,6 +24,9 @@ class TestModelverseCore(unittest.TestCase):
     def test_po_list(self):
         self.list("PO")
 
+    def test_co_list(self):
+        self.list("CO")
+
     def list(self, mode):
         self.assertTrue(run_file(all_files,
             [ "root", "root", "root", 

+ 34 - 29
interface/HUTN/grammars/actionlanguage.g

@@ -1,10 +1,6 @@
 grammar{
     start: (include | vardecl | definition | funcdecl | newline)+;
 
-    definition : type_specifier ID ASSIGN atomvalue;
-
-    include: INCLUDE STRVALUE newline+;
-
     statement 
         : (vardecl newline)
         | (assignment newline)
@@ -12,18 +8,21 @@ grammar{
         | (func_call newline)
         | ifelse
         | while
+        | (continue newline)
+        | (break newline)
         | newline @Rm;
 
-    vardecl: type_specifier ID;
+    primary
+        :   parenthesized
+        |   rvalue
+        |   func_call
+        |   atomvalue;
 
-    assignment
-        :   lvalue ASSIGN expression;
+    assignment: lvalue ASSIGN expression;
 
-    expression
-        :   binary_operation;
+    expression: binary_operation;
 
-	binary_operation
-	    :   disjunction;
+	binary_operation: disjunction;
 
     disjunction
         :   (disjunction OR conjunction)
@@ -60,37 +59,42 @@ grammar{
         |   invert_sign
         |   keep_sign
         |   primary;
-	logical_not
-	    :   NOT primary;
-	invert_sign
-	    :   MINUS primary;
-	keep_sign
-	    :   PLUS primary;
 
-    primary
-        :   parenthesized
-        |   rvalue
-        |   func_call
-        |   atomvalue;
+    rvalue
+        : (rvalue LSQUARE expression RSQUARE)
+        | ID;
 
-    parenthesized
-        :   LPAREN expression RPAREN;
+    vardecl: type_specifier ID;
+
+	logical_not: NOT primary;
+
+	invert_sign: MINUS primary;
+
+	keep_sign: PLUS primary;
+
+    definition : type_specifier ID ASSIGN atomvalue;
+
+    include: INCLUDE STRVALUE newline+;
+
+    continue: CONTINUE EXCLAMATION;
+
+    break: BREAK EXCLAMATION;
+
+    parenthesized: LPAREN expression RPAREN;
 
     atomvalue: string | integer | float | bool | type_specifier | actionname | deref;
 
     deref: QUESTIONMARK ANYTHING?;
 
     type_specifier: INT | FLOAT | BOOL | STRING | TYPE | ACTION | ELEMENT;
+
     actionname: IF_NODE | WHILE_NODE | ASSIGN_NODE | CALL_NODE | BREAK_NODE | CONTINUE_NODE | RETURN_NODE | RESOLVE_NODE | ACCESS_NODE | CONSTANT_NODE | GLOBAL_NODE | DECLARE_NODE | INPUT_NODE | OUTPUT_NODE;
 
     string: (STRVALUE|LONG_STRVALUE);
 
     integer: DEC_NUMBER;
-    float: FLOAT_NUMBER;
 
-    rvalue
-        : (rvalue LSQUARE expression RSQUARE)
-        | ID;
+    float: FLOAT_NUMBER;
 
     lvalue: ID;
 
@@ -148,11 +152,12 @@ grammar{
 
         FUNCTION: 'function';
         RETURN: 'return';
-
         WHILE: 'while';
         IF: 'if';
         ELSE: 'else';
         ELIF: 'elif';
+        CONTINUE: 'continue';
+        BREAK: 'break';
 
         INT: 'Integer';
         FLOAT: 'Float';

+ 9 - 1
interface/HUTN/hutn_compiler/constructors_visitor.py

@@ -41,7 +41,7 @@ class ConstructorsVisitor(Visitor):
         if last.head == "func_call":  # pop 'false'
             self.constructors.pop()
         if new_constructors_were_added:
-            if last.head != "return":
+            if last.head not in frozenset(["return", "continue", "break"]):
                 self.add_constructors(False)
         elif self.constructors:
             self.constructors.pop()  # pop 'true'
@@ -256,6 +256,14 @@ class ConstructorsVisitor(Visitor):
         self.add_constructors(symbol.node)
         self.free_id += 1
 
+    def visit_continue(self, tree):
+        self.add_constructors("continue")
+        return True
+
+    def visit_break(self, tree):
+        self.add_constructors("break")
+        return True
+        
     def visit_return(self, tree):
         self.add_constructors("return")
         if len(tree.get_tail()) > 2:

+ 13 - 1
interface/HUTN/hutn_compiler/primitives_visitor.py

@@ -13,6 +13,7 @@ class PrimitivesVisitor(Visitor):
         self.free_id = 0
         self.function_values = dict()
         self.debug_symbols = "--debug" in args
+        self.while_stack = []
 
     def debug(self, node, tree, msg=""):
         if self.debug_symbols:
@@ -296,10 +297,21 @@ class PrimitivesVisitor(Visitor):
 
         self.set_primitive(tree, first)
 
+    def visit_continue(self, tree):
+        w = self.value(Action("continue"))
+        self.dict(w, "while", self.while_stack[-1])
+
+    def visit_break(self, tree):
+        w = self.value(Action("break"))
+        self.dict(w, "while", self.while_stack[-1])
+
     def visit_while(self, tree):
+        w = self.value(Action("while"))
+
+        self.while_stack.append(w)
         self.visit_children(tree)
+        self.while_stack.pop()
 
-        w = self.value(Action("while"))
         self.debug(w, tree)
         c = self.get_primitive(tree.get_child("expression"))
         b = self.get_primitive(tree.get_child("block"))

+ 19 - 0
interface/HUTN/hutn_compiler/semantics_visitor.py

@@ -14,6 +14,9 @@ class SemanticsVisitor(Visitor):
         # there is only one input file, list is for sharing it among visitors
         self.inputfiles = []
 
+        # Count whether we are in a while or not
+        self.while_counter = 0
+
         # inherited attribute, set in funcdecl and used in return,
         # to ensure that (returned type == declared type)
         self.current_funcdecl = None
@@ -591,7 +594,9 @@ class SemanticsVisitor(Visitor):
             self.check_predicate(expression)
 
     def visit_while(self, tree):
+        self.while_counter += 1
         self.visit_children(tree)
+        self.while_counter -= 1
         expression = tree.get_child("expression")
         self.check_predicate(expression)
 
@@ -640,3 +645,17 @@ class SemanticsVisitor(Visitor):
 
     def visit_bool(self, tree):
         self.set_type(tree, types_mv.Boolean())
+
+    def visit_break(self, tree):
+        if self.while_counter == 0:
+            raise RuntimeError(
+                "{}:{}:{}: error: break outside of while".format(
+                    self.inputfiles[0], tree.startpos['line'],
+                    tree.startpos['column']))
+
+    def visit_continue(self, tree):
+        if self.while_counter == 0:
+            raise RuntimeError(
+                "{}:{}:{}: error: continue outside of while".format(
+                    self.inputfiles[0], tree.startpos['line'],
+                    tree.startpos['column']))

+ 44 - 8
kernel/modelverse_kernel/legacy.py

@@ -14,6 +14,7 @@ else:
 
 class ModelverseKernel(object):
     def __init__(self, root):
+        print("INIT")
         self.root = root
         self.primitives = {}
         self.compiled = {}
@@ -77,7 +78,7 @@ class ModelverseKernel(object):
                 elif inst_v is None:
                     raise Exception("%s: error understanding command (%s, %s)" % (self.debug_info[username], inst_v, self.phase_v))
                 else:
-                    #print("%-30s(%s) -- %s" % (inst_v["value"], self.phase_v, username))
+                    print("%-30s(%s) -- %s" % (inst_v["value"], self.phase_v, username))
                     gen = getattr(self, "%s_%s" % (inst_v["value"], self.phase_v))(user_root)
             elif inst_v is None:
                 raise Exception("%s: error understanding command (%s, %s)" % (self.debug_info[username], inst_v, self.phase_v))
@@ -193,7 +194,7 @@ class ModelverseKernel(object):
     #############################################
     ### Transformation rules for instructions ###
     #############################################
-    def break_init(self, user_root):
+    def continue_init(self, user_root):
         user_frame, =       yield [("RD", [user_root, "frame"])]
         phase_link, ip_link = \
                             yield [("RDE", [user_frame, "phase"]),
@@ -210,14 +211,49 @@ class ModelverseKernel(object):
                                    ("DE", [ip_link]),
                                   ]
 
-    def continue_init(self, user_root):
+    def break_init(self, user_root):
+        print("New break!")
+        raise Exception()
         user_frame, =       yield [("RD", [user_root, "frame"])]
-        ip_link, inst =     yield [("RDE", [user_frame, "IP"]),
-                                   ("RD", [user_frame, "IP"]),
-                                  ]
+        inst, =             yield [("RD", [user_frame, "IP"])]
         while_inst, =       yield [("RD", [inst, "while"])]
-        _, _ =              yield [("CD", [user_frame, "IP", while_inst]),
-                                   ("DE", [ip_link]),
+        old_evalstack_link, old_phase_link, evalstack_roots = \
+                            yield [("RD", [user_frame, "evalstack"]),
+                                   ("RDE", [inst, "phase"]),
+                                   ("RRD", [while_inst, "inst"]),
+                                  ]
+
+        if len(evalstack_roots) == 1:
+            evalstack_root = evalstack_roots[0]
+        else:
+            raise Exception("Could not process continue statement!")
+
+        prev_evalstack_roots, old_evalstack_phase_link = \
+                            yield [("RRD", [evalstack_root, "prev"]),
+                                   ("RDE", [evalstack_root, "phase"]),
+                                  ]
+
+        if len(prev_evalstack_roots) == 1:
+            prev_evalstack_root = prev_evalstack_roots[0]
+        else:
+            raise Exception("Could not process continue statement!")
+
+        new_evalstack_root, new_phase_while, new_phase_inst, prev_evalstack_root_link = \
+                            yield [("CN", []),
+                                   ("CNV", ["finish"]),
+                                   ("CNV", ["finish"]),
+                                   ("CDE", [prev_evalstack_root, "prev"]),
+                                  ]
+
+        _, _, _, _, _, _, _, _  = \
+                            yield [("CD", [user_frame, "evalstack", new_evalstack_root]),
+                                   ("CD", [new_evalstack_root, "prev", prev_evalstack_root]),
+                                   ("CD", [inst, "phase", new_phase_inst]),
+                                   ("CD", [prev_evalstack_root, "phase", new_phase_while]),
+                                   ("DE", [old_evalstack_link]),
+                                   ("DE", [prev_evalstack_root_link]),
+                                   ("DE", [old_phase_link]),
+                                   ("DE", [old_evalstack_phase_link]),
                                   ]
 
     def if_init(self, user_root):

+ 2 - 0
kernel/modelverse_kernel/primitives.py

@@ -503,6 +503,8 @@ def deserialize(a, root, **remainder):
             name, temp = constructor.split("(", 1)
             string_value = temp[:-1]
             if string_value in complex_primitives:
+                if string_value == "break":
+                    print("Deserialize break")
                 value = {"value": string_value}
             else:
                 #TODO this is very dangerous!

+ 1 - 1
scripts/run_local_modelverse.py

@@ -7,4 +7,4 @@ if len(sys.argv) < 2:
     sys.stderr.write("    %s port\n" % sys.argv[0])
 else:
     subprocess.check_call([sys.executable, "-m", "sccd.compiler.sccdc", "-p", "threads", "server.xml"], cwd="hybrid_server")
-    subprocess.call([sys.executable, "run_mvk_server.py"] + sys.argv[1:], cwd="hybrid_server")
+    subprocess.call([sys.executable, "run_mvk_server.py"] + sys.argv[1:] + ["--kernel=legacy-interpreter"], cwd="hybrid_server")