generate_IEC_std.py
changeset 25 8dc68e669d99
child 26 36d378bd852e
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/generate_IEC_std.py	Fri Jul 06 18:55:52 2007 +0200
@@ -0,0 +1,412 @@
+# Get definitions
+from plcopen.structures import *
+
+#import pprint
+#pp = pprint.PrettyPrinter(indent=4)
+
+def ANY_to_compiler_test_type_GEN(typename, paramname):
+    """
+    Convert ANY_XXX IEC type declaration into IEC2CC's generated type test.
+    This tests are defined in search_expression_type.cc 
+    """
+    return {"ANY" : "",
+    "ANY_BIT" : "if(search_expression_type->is_binary_type(%(paramname)s_type_symbol))",
+    "ANY_NUM" : "if(search_expression_type->is_num_type(%(paramname)s_type_symbol))",
+    "ANY_REAL" : "if(search_expression_type->is_real_type(%(paramname)s_type_symbol))",
+    "ANY_INT" : "if(search_expression_type->is_integer_type(%(paramname)s_type_symbol))"
+    }.get(typename,
+        "if (typeid(*last_type_symbol) == typeid(%(typename)s_type_name_c))")%{
+                "paramname" : paramname, "typename": typename.lower()}
+
+def recurse_and_indent(fdecls, indent, do_type_search_only = False, do_il = False):
+    """
+    This function generate visit(function_invocation) code for 
+        - ST code generator
+        - IL code generator
+        - search_expression_type class for ST
+        - search_expression_type class for IL
+        
+    Input data is a 
+    "{fname : {IN[0]paramname : {IN[0]paramtype : {IN[1]paraname : {IN[1]paramtype : {... : {IN[N]paraname : {IN[N]paramtype : (fdecl,)}}}}}}"
+    nested dictionary structure.
+    """
+    if type(fdecls) != type(tuple()):
+        res = ""
+        for Paramname, ParamTypes in fdecls.iteritems():
+            if do_il:
+                res += """
+{"""
+                if not do_type_search_only:
+                    res += """
+    /* Get the value from a foo(<param_name> = <param_value>) style call */
+    symbol_c *%(input_name)s_param_value = &this->default_variable_name;
+"""%{"input_name":Paramname}
+                res += """
+    symbol_c *%(input_name)s_type_symbol = param_data_type;
+    last_type_symbol = param_data_type;
+"""%{"input_name":Paramname}
+            else:
+                res += """
+{
+    identifier_c param_name("%(input_name)s");
+    /* Get the value from a foo(<param_name> = <param_value>) style call */
+    symbol_c *%(input_name)s_param_value = function_call_param_iterator.search(&param_name);
+    
+    /* Get the value from a foo(<param_value>) style call */
+    if (%(input_name)s_param_value == NULL)
+      %(input_name)s_param_value = function_call_param_iterator.next();
+    symbol_c *%(input_name)s_type_symbol = search_expression_type->get_type(%(input_name)s_param_value);
+    last_type_symbol = last_type_symbol && search_expression_type->is_same_type(%(input_name)s_type_symbol, last_type_symbol) ? search_expression_type->common_type(%(input_name)s_type_symbol, last_type_symbol) : %(input_name)s_type_symbol ;
+"""%{"input_name":Paramname}
+            
+            for ParamType,NextParamDecl in ParamTypes.iteritems():
+            
+                res += """    
+    %(type_test)s
+    {
+%(if_good_type_code)s
+    }
+"""%{
+    "type_test":ANY_to_compiler_test_type_GEN(ParamType,Paramname), 
+    "if_good_type_code":recurse_and_indent(NextParamDecl,indent,do_type_search_only).replace('\n','\n    ')}
+
+            res += """    
+    ERROR;
+}
+"""
+        
+        return res.replace('\n','\n'+indent)
+    else:
+        res = "\n"
+        fdecl=fdecls[0]
+        
+        result_type_rule = fdecl["return_type_rule"]
+        res += {
+            "copy_input" : "symbol_c * return_type_symbol = last_type_symbol;\n",
+            "defined" : "symbol_c * return_type_symbol = &search_constant_type_c::%s_type_name;\n"%fdecl["outputs"][0][1].lower(),
+            }.get(result_type_rule, "symbol_c * return_type_symbol = %s;\n"%result_type_rule)
+        
+        if not do_type_search_only:
+            code_gen = eval(fdecl["python_eval_c_code_format"])
+
+            code_gen_dic_decl = {}
+            for paramname,paramtype,unused in fdecl["inputs"]:
+                code_gen_dic_decl[paramname+"_value"] = '");\n%s_param_value->accept(*this);\ns4o.print("'%(paramname)
+                code_gen_dic_decl[paramname+"_type"] = '");\n%s_type_symbol->accept(*this);\ns4o.print("'%(paramname)
+            code_gen_dic_decl["return_type"] = '");\nreturn_type_symbol->accept(*this);\ns4o.print("'
+            code_gen_dic_decl["param_count"] = '");\ns4o.print_integer(nb_param);\ns4o.print("'
+            code_gen_dic_decl["start_bool_filter"] = '");\nif (search_expression_type->is_bool_type(last_type_symbol))\n  s4o.print("('
+            code_gen_dic_decl["end_bool_filter"] = '");\nif (search_expression_type->is_bool_type(last_type_symbol)) {\n  s4o.print("&1");\n  s4o.print(")");\n}\ns4o.print("'
+            
+            if type(code_gen) == type(tuple()):
+                res += 's4o.print("%s");\n'%(code_gen[0]%code_gen_dic_decl)
+                static_param_accept_list = []
+                for paramname,paramtype,unused in fdecl["inputs"]:
+                    static_param_accept_list.append("%s_param_value->accept(*this);\n"%(paramname))
+                res += ('s4o.print("%s");\n'%(code_gen[1])).join(static_param_accept_list)
+                code = 's4o.print("%s");\nparam_value->accept(*this);\n'%(code_gen[1])
+                end_code = 's4o.print("%s");\nreturn NULL;\n'%(code_gen[2]%code_gen_dic_decl)
+            else:
+                code = ''
+                end_code = ('s4o.print("' + code_gen%code_gen_dic_decl + '");\nreturn NULL;\n').replace('s4o.print("");\n','')
+
+            if fdecl["extensible"]:
+                res += ("""
+int base_num = %d;
+symbol_c *param_value = NULL;
+do{
+    char my_name[10];
+    sprintf(my_name, "IN%%d", base_num++);
+    identifier_c param_name(my_name);
+    
+    /* Get the value from a foo(<param_name> = <param_value>) style call */
+    param_value = function_call_param_iterator.search(&param_name);
+    
+    /* Get the value from a foo(<param_value>) style call */
+    if (param_value == NULL)
+      param_value = function_call_param_iterator.next();
+    if (param_value != NULL){
+        symbol_c *current_type_symbol = search_expression_type->get_type(param_value);
+        last_type_symbol = last_type_symbol && search_expression_type->is_same_type(current_type_symbol, last_type_symbol) ? search_expression_type->common_type(current_type_symbol, last_type_symbol) : current_type_symbol ;
+    
+        /*Function specific CODE */
+        %s
+    }
+    
+}while(param_value != NULL);
+%s
+"""%(fdecl["baseinputnumber"]+2, code.replace('\n','\n        '), end_code))
+            else:
+                #res += code + end_code
+                res += end_code
+        else:
+            res += "return return_type_symbol;\n"
+        
+                
+        return res.replace('\n','\n'+indent)
+
+###################################################################
+###                                                             ###
+###                           MAIN                              ###
+###                                                             ###
+###################################################################
+
+"""
+Reorganize std_decl from structure.py
+into a nested dictionnary structure (i.e. a tree):
+"{fname : {IN[0]paramname : {IN[0]paramtype : {IN[1]paraname : {IN[1]paramtype : {... : {IN[N]paraname : {IN[N]paramtype : (fdecl,)}}}}}}"
+Keep ptrack of original declaration order in a 
+separated list called official_order
+"""
+std_fdecls = {}
+official_order = []
+for section in std_decl:
+    for fdecl in section["list"]:
+        if len(official_order)==0 or official_order[-1] != fdecl["name"]:
+            official_order.append(fdecl["name"])
+        # store all func by name in a dict
+        std_fdecls_fdecl_name = std_fdecls.get(fdecl["name"], {})
+        current = std_fdecls_fdecl_name
+        for i in fdecl["inputs"]:
+            current[i[0]] = current.get(i[0], {})
+            current = current[i[0]]
+            last = current
+            current[i[1]] = current.get(i[1], {})
+            current = current[i[1]]
+        last[i[1]]=(fdecl,)
+        std_fdecls[fdecl["name"]] = std_fdecls_fdecl_name
+
+###################################################################
+
+"""
+Generate the long enumeration of std function types
+"""
+function_type_decl =  """
+/****
+ * IEC 61131-3 standard function lib
+ * generated code, do not edit by hand
+ */
+typedef enum {
+"""
+for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]:
+    function_type_decl += "    function_"+fname.lower()+",\n"
+
+function_type_decl += """    function_none
+} function_type_t;
+"""
+###################################################################
+"""
+Generate the funct that return enumerated according function name
+"""
+get_function_type_decl = """
+/****
+ * IEC 61131-3 standard function lib
+ * generated code, do not edit by hand
+ */
+function_type_t get_function_type(identifier_c *function_name) {
+"""
+for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]:
+    get_function_type_decl += """
+if (!strcasecmp(function_name->value, "%s"))
+    return function_%s;
+"""%(fname,fname.lower())
+
+get_function_type_decl += """
+    else return function_none;
+}
+
+"""
+###################################################################
+"""
+Generate the part of generate_cc_st_c::visit(function_invocation)
+that is responsible to generate C code for std lib calls.
+"""
+st_code_gen = """
+/****
+ * IEC 61131-3 standard function lib
+ * generated code, do not edit by hand
+ */
+switch(current_function_type){
+"""
+
+for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]:
+    st_code_gen += """
+/****
+ *%s
+ */
+    case function_%s :
+    {
+        symbol_c *last_type_symbol = NULL;
+"""    %(fname, fname.lower())
+    indent =  "    "
+
+    st_code_gen += recurse_and_indent(fdecls, indent).replace('\n','\n    ')
+    
+    st_code_gen += """
+    }/*function_%s*/
+    break;
+"""    %(fname.lower())
+st_code_gen +=  """
+    case function_none :
+    ERROR;
+}
+return NULL;
+"""
+
+###################################################################
+"""
+Generate the part of generate_cc_il_c::visit(il_function_call)
+that is responsible to generate C code for std lib calls.
+"""
+il_code_gen = """
+/****
+ * IEC 61131-3 standard function lib
+ * generated code, do not edit by hand
+ */
+switch(current_function_type){
+"""
+
+for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]:
+    il_code_gen += """
+/****
+ *%s
+ */
+    case function_%s :
+    {
+        symbol_c *last_type_symbol = NULL;
+"""    %(fname, fname.lower())
+    indent =  "    "
+
+    il_code_gen += recurse_and_indent(fdecls, indent, do_il=True).replace('\n','\n    ')
+    
+    il_code_gen += """
+    }/*function_%s*/
+    break;
+"""    %(fname.lower())
+il_code_gen +=  """
+    case function_none :
+    ERROR;
+}
+return NULL;
+"""
+
+###################################################################
+"""
+Generate the part of search_expression_type_c::visit(function_invocation)
+that is responsible of returning type symbol for function invocation.
+"""
+search_type_code =  """
+/****
+ * IEC 61131-3 standard function lib
+ * generated code, do not edit by hand
+ */
+
+void *compute_standard_function_st(function_invocation_c *symbol) {
+
+  function_type_t current_function_type = get_function_type((identifier_c *)symbol->function_name);
+  function_call_param_iterator_c function_call_param_iterator(symbol);
+  search_expression_type_c* search_expression_type = this;
+
+  switch(current_function_type){
+"""
+
+for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]:
+    search_type_code += """
+/****
+ *%s
+ */
+    case function_%s :
+    {
+        symbol_c *last_type_symbol = NULL;
+"""    %(fname, fname.lower())
+    indent =  "    "
+
+    search_type_code += recurse_and_indent(fdecls, indent, True).replace('\n','\n    ')
+    
+    search_type_code += """
+    }/*function_%s*/
+    break;
+"""    %(fname.lower())
+search_type_code += """
+    case function_none :
+    ERROR;
+  }
+  return NULL;
+}
+
+void *compute_standard_function_il(il_function_call_c *symbol, symbol_c *param_data_type) {
+  
+  function_type_t current_function_type = get_function_type((identifier_c *)symbol->function_name);
+  function_call_param_iterator_c function_call_param_iterator(symbol);  
+  search_expression_type_c* search_expression_type = this;
+
+  switch(current_function_type){
+"""
+
+for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]:
+    search_type_code += """
+/****
+ *%s
+ */
+    case function_%s :
+    {
+        symbol_c *last_type_symbol = NULL;
+"""    %(fname, fname.lower())
+    indent =  "    "
+
+    search_type_code += recurse_and_indent(fdecls, indent, True, True).replace('\n','\n    ')
+    
+    search_type_code += """
+    }/*function_%s*/
+    break;
+"""    %(fname.lower())
+search_type_code += """
+    case function_none :
+    ERROR;
+  }
+  return NULL;
+}
+"""
+
+###################################################################
+###################################################################
+###################################################################
+"""
+Generate the C implementation of the IEC standard function library.
+"""
+iec_std_lib_generated =  """
+/****
+ * IEC 61131-3 standard function lib
+ * generated code, do not edit by hand
+ */
+
+/* Macro that expand to subtypes */
+"""
+for typename, parenttypename in TypeHierarchy_list:
+    if (typename.startswith("ANY")):
+        iec_std_lib_generated += "#define " + typename + "(DO)"
+        for typename2, parenttypename2 in TypeHierarchy_list:
+            if(parenttypename2 == typename):
+                if(typename2.startswith("ANY")):
+                    iec_std_lib_generated +=  " " + typename2 + "(DO)"
+                else:
+                    iec_std_lib_generated +=  " DO(" + typename2 + ")"
+        iec_std_lib_generated +=  "\n"
+    else:
+        break
+
+if len(sys.argv) != 2 :
+    print "Usage: " + sys.argv[0] + "path_name\n -> create files in path_name"
+    sys.exit(0)
+
+# Now, print that out, or write to files from sys.argv
+for name, ext in [
+        ('function_type_decl','h'),
+        ('get_function_type_decl','c'),
+        ('st_code_gen','c'),
+        ('il_code_gen','c'),
+        ('search_type_code','c'),
+        ('iec_std_lib_generated','h')]:
+    fd = open(os.path.join(sys.argv[1],name+'.'+ext),'w')
+    fd.write(eval(name))
+    fd.close()