plcopen/structures.py
changeset 25 8dc68e669d99
parent 23 cce8d5662738
child 27 dae55dd9ee14
--- a/plcopen/structures.py	Mon Jun 25 18:57:14 2007 +0200
+++ b/plcopen/structures.py	Fri Jul 06 18:55:52 2007 +0200
@@ -151,29 +151,32 @@
     ("ANY_ELEMENTARY", "ANY"),
     ("ANY_MAGNITUDE", "ANY_ELEMENTARY"),
     ("ANY_BIT", "ANY_ELEMENTARY"),
+    ("ANY_NBIT", "ANY_BIT"),
     ("ANY_STRING", "ANY_ELEMENTARY"),
     ("ANY_DATE", "ANY_ELEMENTARY"),
     ("ANY_NUM", "ANY_MAGNITUDE"),
     ("ANY_REAL", "ANY_NUM"),
     ("ANY_INT", "ANY_NUM"),
+    ("ANY_SINT", "ANY_INT"),
+    ("ANY_UINT", "ANY_INT"),
     ("REAL", "ANY_REAL"),
     ("LREAL", "ANY_REAL"),
-    ("SINT", "ANY_INT"),
-    ("INT", "ANY_INT"),
-    ("DINT", "ANY_INT"),
-    ("LINT", "ANY_INT"),
-    ("USINT", "ANY_INT"),
-    ("UINT", "ANY_INT"),
-    ("UDINT", "ANY_INT"),
-    ("ULINT", "ANY_INT"),
+    ("SINT", "ANY_SINT"),
+    ("INT", "ANY_SINT"),
+    ("DINT", "ANY_SINT"),
+    ("LINT", "ANY_SINT"),
+    ("USINT", "ANY_UINT"),
+    ("UINT", "ANY_UINT"),
+    ("UDINT", "ANY_UINT"),
+    ("ULINT", "ANY_UINT"),
     ("TIME", "ANY_MAGNITUDE"),
     ("BOOL", "ANY_BIT"),
-    ("BYTE", "ANY_BIT"),
-    ("WORD", "ANY_BIT"),
-    ("DWORD", "ANY_BIT"),
-    ("LWORD", "ANY_BIT"),
+    ("BYTE", "ANY_NBIT"),
+    ("WORD", "ANY_NBIT"),
+    ("DWORD", "ANY_NBIT"),
+    ("LWORD", "ANY_NBIT"),
     ("STRING", "ANY_STRING"),
-    ("WSTRING", "ANY_STRING"),
+    #("WSTRING", "ANY_STRING"), # TODO
     ("DATE", "ANY_DATE"),
     ("TOD", "ANY_DATE"),
     ("DT", "ANY_DATE")]
@@ -331,20 +334,51 @@
     return params
 
 
-ANY_T0_ANY_LIST=[
+ANY_TO_ANY_LIST=[
+        # simple type conv are let as C cast
         (("ANY_NUM","ANY_BIT"),("ANY_NUM","ANY_BIT"), "(%(return_type)s)%(IN_value)s"),
-        (("ANY_NUM","ANY_BIT"),("ANY_DATE","TIME"), "(%(return_type)s)real_to_time(%(IN_value)s)"), 
-        (("ANY_DATE","TIME"), ("ANY_NUM","ANY_BIT"), "(%(return_type)s)time_to_real(%(IN_value)s)"), 
-        (("ANY_DATE","TIME"), ("ANY_STRING",), "(%(return_type)s)time_to_string(%(IN_value)s)"),
-        (("ANY_STRING",), ("ANY_DATE","TIME"), "(%(return_type)s)string_to_time(%(IN_value)s)"),
-        (("ANY_BIT",), ("ANY_STRING",), "(%(return_type)s)int_to_string(%(IN_value)s, 16)"),
-        (("ANY_NUM",), ("ANY_STRING",), "(%(return_type)s)int_to_string(%(IN_value)s, 10)"),
-        (("ANY_STRING",), ("ANY_BIT",), "(%(return_type)s)string_to_int(%(IN_value)s, 16)"),
-        (("ANY_STRING",), ("ANY_NUM",), "(%(return_type)s)string_to_int(%(IN_value)s, 10)")]
-
-def ANY_TO_ANY_FORMAT_GEN(fdecl):
-
-    for (InTypes, OutTypes, Format) in ANY_T0_ANY_LIST:
+        # TO_TIME
+        (("ANY_INT","ANY_BIT"),("ANY_DATE","TIME"), "(%(return_type)s)__int_to_time(%(IN_value)s)"),
+        (("ANY_REAL",),("ANY_DATE","TIME"), "(%(return_type)s)__real_to_time(%(IN_value)s)"),
+        (("ANY_STRING",), ("ANY_DATE","TIME"), "(%(return_type)s)__string_to_time(%(IN_value)s)"),
+        # FROM_TIME
+        (("ANY_DATE","TIME"), ("ANY_REAL",), "(%(return_type)s)__time_to_real(%(IN_value)s)"),
+        (("ANY_DATE","TIME"), ("ANY_INT","ANY_BIT"), "(%(return_type)s)__time_to_int(%(IN_value)s)"),
+        (("TIME",), ("ANY_STRING",), "(%(return_type)s)__time_to_string(%(IN_value)s)"),
+        (("DATE",), ("ANY_STRING",), "(%(return_type)s)__date_to_string(%(IN_value)s)"),
+        (("TOD",), ("ANY_STRING",), "(%(return_type)s)__tod_to_string(%(IN_value)s)"),
+        (("DT",), ("ANY_STRING",), "(%(return_type)s)__dt_to_string(%(IN_value)s)"),
+        # TO_STRING
+        (("BOOL",), ("ANY_STRING",), "(%(return_type)s)__bool_to_string(%(IN_value)s)"),
+        (("ANY_BIT",), ("ANY_STRING",), "(%(return_type)s)__bit_to_string(%(IN_value)s)"),
+        (("ANY_REAL",), ("ANY_STRING",), "(%(return_type)s)__real_to_string(%(IN_value)s)"),
+        (("ANY_SINT",), ("ANY_STRING",), "(%(return_type)s)__sint_to_string(%(IN_value)s)"),
+        (("ANY_UINT",), ("ANY_STRING",), "(%(return_type)s)__uint_to_string(%(IN_value)s)"),
+        # FROM_STRING
+        (("ANY_STRING",), ("BOOL",), "(%(return_type)s)__string_to_bool(%(IN_value)s)"),
+        (("ANY_STRING",), ("ANY_BIT",), "(%(return_type)s)__string_to_bit(%(IN_value)s)"),
+        (("ANY_STRING",), ("ANY_SINT",), "(%(return_type)s)__string_to_sint(%(IN_value)s)"),
+        (("ANY_STRING",), ("ANY_UINT",), "(%(return_type)s)__string_to_uint(%(IN_value)s)"),
+        (("ANY_STRING",), ("ANY_REAL",), "(%(return_type)s)__string_to_real(%(IN_value)s)")]
+
+
+BCD_TO_ANY_LIST=[
+        (("BYTE",),("USINT",), "(%(return_type)s)__bcd_to_uint(%(IN_value)s)"),
+        (("WORD",),("UINT",), "(%(return_type)s)__bcd_to_uint(%(IN_value)s)"),
+        (("DWORD",),("UDINT",), "(%(return_type)s)__bcd_to_uint(%(IN_value)s)"),
+        (("LWORD",),("ULINT",), "(%(return_type)s)__bcd_to_uint(%(IN_value)s)")]
+
+
+ANY_TO_BCD_LIST=[
+        (("USINT",),("BYTE",), "(%(return_type)s)__uint_to_bcd(%(IN_value)s)"),
+        (("UINT",),("WORD",), "(%(return_type)s)__uint_to_bcd(%(IN_value)s)"),
+        (("UDINT",),("DWORD",), "(%(return_type)s)__uint_to_bcd(%(IN_value)s)"),
+        (("ULINT",),("LWORD",), "(%(return_type)s)__uint_to_bcd(%(IN_value)s)")]
+
+
+def ANY_TO_ANY_FORMAT_GEN(any_to_any_list, fdecl):
+
+    for (InTypes, OutTypes, Format) in any_to_any_list:
         outs = reduce(lambda a,b: a or b, map(lambda testtype : IsOfType(fdecl["outputs"][0][1],testtype), OutTypes))
         inps = reduce(lambda a,b: a or b, map(lambda testtype : IsOfType(fdecl["inputs"][0][1],testtype), InTypes))
         if inps and outs and fdecl["outputs"][0][1] != fdecl["inputs"][0][1]:
@@ -396,14 +430,11 @@
                         Function_decl[param] = translate[param](value)
                 Function_decl["type"] = "function"
                 
-                if Function_decl["name"].startswith('*') :
+                if Function_decl["name"].startswith('*') or Function_decl["name"].endswith('*') :
                     input_ovrloading_types = GetSubTypes(Function_decl["inputs"][0][1])
+                    output_types = GetSubTypes(Function_decl["outputs"][0][1])
                 else:
                     input_ovrloading_types = [None]
-                    
-                if Function_decl["name"].endswith('*') :
-                    output_types = GetSubTypes(Function_decl["outputs"][0][1])
-                else:
                     output_types = [None]
                     
                 funcdeclname_orig = Function_decl["name"]
@@ -458,359 +489,7 @@
     
     return Standard_Functions_Decl
 
-
-if __name__ == '__main__':
-    
-    import pprint
-    pp = pprint.PrettyPrinter(indent=4)
-
-    def ANY_to_compiler_test_type_GEN(typename, paramname):
-        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):
-        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                              ###
-###                                                             ###
-###################################################################
-
-    # Get definitions
-    std_decl = get_standard_funtions(csv_file_to_table(open("iec_std.csv")))#, True)
-    
-    # Reorganize into a dict of dict, according 
-    # fname : paramname : paramtype : paraname : paramtype...
-    # Keep ptrack of original order in a separated list
-    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 thaat 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;
-}
-"""
-
-
-    # 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')]:
-        fd = open(os.path.join(sys.argv[1],name+'.'+ext),'w')
-        fd.write(eval(name))
-        fd.close()
-else:
-    # Put standard functions declaration in Bloktypes
-    BlockTypes.extend(get_standard_funtions(csv_file_to_table(open(os.path.join(sys.path[0], "plcopen/iec_std.csv")))))
-
-    
\ No newline at end of file
+std_decl = get_standard_funtions(csv_file_to_table(open(os.path.join(os.path.split(__file__)[0],"iec_std.csv"))))#, True)
+
+BlockTypes.extend(std_decl)
+