plcopen/structures.py
author lbessard
Thu, 21 Jun 2007 10:23:26 +0200
changeset 23 cce8d5662738
parent 22 a765fae3b361
child 25 8dc68e669d99
permissions -rw-r--r--
Code for il generation finished
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import string, os, sys

#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
#based on the plcopen standard. 
#
#Copyright (C): Edouard TISSERANT and Laurent BESSARD
#
#See COPYING file for copyrights details.
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#Lesser General Public License for more details.
#
#You should have received a copy of the GNU General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


LANGUAGES = ["IL","ST","FBD","LD","SFC"]


#-------------------------------------------------------------------------------
#                        Function Block Types definitions
#-------------------------------------------------------------------------------


"""
Ordored list of common Function Blocks defined in the IEC 61131-3
Each block have this attributes:
    - "name" : The block name
    - "type" : The block type. It can be "function", "functionBlock" or "program"
    - "extensible" : Boolean that define if the block is extensible
    - "inputs" : List of the block inputs
    - "outputs" : List of the block outputs
    - "comment" : Comment that will be displayed in the block popup
Inputs and outputs are a tuple of characteristics that are in order:
    - The name
    - The data type
    - The default modifier which can be "none", "negated", "rising" or "falling"
"""

BlockTypes = [{"name" : "Standard function blocks", "list":
               [{"name" : "SR", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("S1","BOOL","none"),("R","BOOL","none")], 
                    "outputs" : [("Q1","BOOL","none")],
                    "comment" : "SR bistable\nThe SR bistable is a latch where the Set dominates."},
                {"name" : "RS", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("S","BOOL","none"),("R1","BOOL","none")], 
                    "outputs" : [("Q1","BOOL","none")],
                    "comment" : "RS bistable\nThe RS bistable is a latch where the Reset dominates."},
                {"name" : "SEMA", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("CLAIM","BOOL","none"),("RELEASE","BOOL","none")], 
                    "outputs" : [("BUSY","BOOL","none")],
                    "comment" : "Semaphore\nThe semaphore provides a mechanism to allow software elements mutually exclusive access to certain ressources."},
                {"name" : "R_TRIG", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("CLK","BOOL","none")], 
                    "outputs" : [("Q","BOOL","none")],
                    "comment" : "Rising edge detector\nThe output produces a single pulse when a rising edge is detected."},
                {"name" : "F_TRIG", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("CLK","BOOL","none")], 
                    "outputs" : [("Q","BOOL","none")],
                    "comment" : "Falling edge detector\nThe output produces a single pulse when a falling edge is detected."},
                {"name" : "CTU", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("CU","BOOL","rising"),("R","BOOL","none"),("PV","INT","none")], 
                    "outputs" : [("Q","BOOL","none"),("CV","INT","none")],
                    "comment" : "Up-counter\nThe up-counter can be used to signal when a count has reached a maximum value."},
                {"name" : "CTD", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("CD","BOOL","rising"),("LD","BOOL","none"),("PV","INT","none")], 
                    "outputs" : [("Q","BOOL","none"),("CV","INT","none")],
                    "comment" : "Down-counter\nThe down-counter can be used to signal when a count has reached zero, on counting down from a preset value."},
                {"name" : "CTUD", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("CU","BOOL","rising"),("CD","BOOL","rising"),("R","BOOL","none"),("LD","BOOL","none"),("PV","INT","none")], 
                    "outputs" : [("QU","BOOL","none"),("QD","BOOL","none"),("CV","INT","none")],
                    "comment" : "Up-down counter\nThe up-down counter has two inputs CU and CD. It can be used to both count up on one input ans down on the other."},
                {"name" : "TP", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], 
                    "outputs" : [("Q","BOOL","none"),("ET","TIME","none")],
                    "comment" : "Pulse timer\nThe pulse timer can be used to generate output pulses of a given time duration."},
                {"name" : "TOF", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], 
                    "outputs" : [("Q","BOOL","none"),("ET","TIME","none")],
                    "comment" : "On-delay timer\nThe on-delay timer can be used to delay setting an output true, for fixed period after an input becomes true."},
                {"name" : "TON", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], 
                    "outputs" : [("Q","BOOL","none"),("ET","TIME","none")],
                    "comment" : "Off-delay timer\nThe off-delay timer can be used to delay setting an output false, for fixed period after input goes false."},
                {"name" : "RTC", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("EN","BOOL","none"),("PDT","DATE_AND_TIME","none")], 
                    "outputs" : [("Q","BOOL","none"),("CDT","DATE_AND_TIME","none")],
                    "comment" : "Real time clock\nThe real time clock has many uses including time stamping, setting dates and times of day in batch reports, in alarm messages and so on."},
                {"name" : "INTEGRAL", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("RUN","BOOL","none"),("R1","BOOL","none"),("XIN","REAL","none"),("X0","REAL","none"),("CYCLE","TIME","none")], 
                    "outputs" : [("Q","BOOL","none"),("XOUT","REAL","none")],
                    "comment" : "Integral\nThe integral function block integrates the value of input XIN over time."},
                {"name" : "DERIVATIVE", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("RUN","BOOL","none"),("XIN","REAL","none"),("CYCLE","TIME","none")], 
                    "outputs" : [("XOUT","REAL","none")],
                    "comment" : "Derivative\nThe derivative function block produces an output XOUT proportional to the rate of change of the input XIN."},
                {"name" : "PID", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("AUTO","BOOL","none"),("PV","REAL","none"),("SP","REAL","none"),("X0","REAL","none"),("KP","REAL","none"),("TR","REAL","none"),("TD","REAL","none"),("CYCLE","TIME","none")], 
                    "outputs" : [("XOUT","REAL","none")],
                    "comment" : "PID\nThe PID (proportional, Integral, Derivative) function block provides the classical three term controller for closed loop control."},
                {"name" : "RAMP", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("RUN","BOOL","none"),("X0","REAL","none"),("X1","REAL","none"),("TR","TIME","none"),("CYCLE","TIME","none"),("HOLDBACK","BOOL","none"),("ERROR","REAL","none"),("PV","REAL","none")], 
                    "outputs" : [("RAMP","BOOL","none"),("XOUT","REAL","none")],
                    "comment" : "Ramp\nThe RAMP function block is modelled on example given in the standard but with the addition of a 'Holdback' feature."},
                {"name" : "HYSTERESIS", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("XIN1","REAL","none"),("XIN2","REAL","none"),("EPS","REAL","none")], 
                    "outputs" : [("Q","BOOL","none")],
                    "comment" : "Hysteresis\nThe hysteresis function block provides a hysteresis boolean output driven by the difference of two floating point (REAL) inputs XIN1 and XIN2."},
                {"name" : "RATIO_MONITOR", "type" : "functionBlock", "extensible" : False, 
                    "inputs" : [("PV1","REAL","none"),("PV2","REAL","none"),("RATIO","REAL","none"),("TIMON","TIME","none"),("TIMOFF","TIME","none"),("TOLERANCE","BOOL","none"),("RESET","BOOL","none"),("CYCLE","TIME","none")], 
                    "outputs" : [("ALARM","BOOL","none"),("TOTAL_ERR","BOOL","none")],
                    "comment" : "Ratio monitor\nThe ratio_monitor function block checks that one process value PV1 is always a given ratio (defined by input RATIO) of a second process value PV2."},
               ]}
             ]

"""
Function that returns the block definition associated to the block type given
"""

def GetBlockType(type):
    for category in BlockTypes:
        for blocktype in category["list"]:
            if blocktype["name"] == type:
                return blocktype
    return None


#-------------------------------------------------------------------------------
#                           Data Types definitions
#-------------------------------------------------------------------------------

"""
Ordored list of common data types defined in the IEC 61131-3
Each type is associated to his direct parent type. It defines then a hierarchy
between type that permits to make a comparison of two types
"""
TypeHierarchy_list = [
    ("ANY", None),
    ("ANY_DERIVED", "ANY"),
    ("ANY_ELEMENTARY", "ANY"),
    ("ANY_MAGNITUDE", "ANY_ELEMENTARY"),
    ("ANY_BIT", "ANY_ELEMENTARY"),
    ("ANY_STRING", "ANY_ELEMENTARY"),
    ("ANY_DATE", "ANY_ELEMENTARY"),
    ("ANY_NUM", "ANY_MAGNITUDE"),
    ("ANY_REAL", "ANY_NUM"),
    ("ANY_INT", "ANY_NUM"),
    ("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"),
    ("TIME", "ANY_MAGNITUDE"),
    ("BOOL", "ANY_BIT"),
    ("BYTE", "ANY_BIT"),
    ("WORD", "ANY_BIT"),
    ("DWORD", "ANY_BIT"),
    ("LWORD", "ANY_BIT"),
    ("STRING", "ANY_STRING"),
    ("WSTRING", "ANY_STRING"),
    ("DATE", "ANY_DATE"),
    ("TOD", "ANY_DATE"),
    ("DT", "ANY_DATE")]

TypeHierarchy = dict(TypeHierarchy_list)

"""
returns true if the given data type is the same that "reference" meta-type or one of its types.
"""

def IsOfType(test, reference):
    while test != None:
        if test == reference:
            return True
        test = TypeHierarchy[test]
    return False

"""
returns list of all types that correspont to the ANY* meta type
"""
def GetSubTypes(reference):
    return [ typename for typename, parenttype in TypeHierarchy_list if typename[:3] != "ANY" and IsOfType(typename, reference)]


#-------------------------------------------------------------------------------
#                             Test identifier
#-------------------------------------------------------------------------------



# Test if identifier is valid
def TestIdentifier(identifier):
     if identifier[0].isdigit():
        return False
     words = identifier.split('_')
     for i, word in enumerate(words):
         if len(word) == 0 and i != 0:
             return False
         if len(word) != 0 and not word.isalnum():
             return False
     return True


#-------------------------------------------------------------------------------
#                            Languages Keywords
#-------------------------------------------------------------------------------


# Keywords for Pou Declaration
POU_KEYWORDS = ["FUNCTION", "END_FUNCTION", "FUNCTION_BLOCK", "END_FUNCTION_BLOCK",
 "PROGRAM", "END_PROGRAM", "EN", "ENO", "F_EDGE", "R_EDGE"]
for category in BlockTypes:
    for block in category["list"]:
        if block["name"] not in POU_KEYWORDS:
            POU_KEYWORDS.append(block["name"])


# Keywords for Type Declaration
TYPE_KEYWORDS = ["TYPE", "END_TYPE", "STRUCT", "END_STRUCT", "ARRAY", "OF", "T",
 "D", "TIME_OF_DAY", "DATE_AND_TIME"]
TYPE_KEYWORDS.extend([keyword for keyword in TypeHierarchy.keys() if keyword not in TYPE_KEYWORDS])


# Keywords for Variable Declaration
VAR_KEYWORDS = ["VAR", "VAR_INPUT", "VAR_OUTPUT", "VAR_IN_OUT", "VAR_TEMP", 
 "VAR_EXTERNAL", "END_VAR", "AT", "CONSTANT", "RETAIN", "NON_RETAIN"]


# Keywords for Configuration Declaration
CONFIG_KEYWORDS = ["CONFIGURATION", "END_CONFIGURATION", "RESOURCE", "ON", "END_RESOURCE",
 "PROGRAM", "WITH", "READ_ONLY", "READ_WRITE", "TASK", "VAR_ACCESS", "VAR_CONFIG", 
 "VAR_GLOBAL", "END_VAR"]


# Keywords for Structured Function Chart
SFC_KEYWORDS = ["ACTION", "END_ACTION", "INITIAL_STEP", "STEP", "END_STEP", "TRANSITION",
 "FROM", "TO", "END_TRANSITION"]


# Keywords for Instruction List
IL_KEYWORDS = ["LD", "LDN", "ST", "STN", "S", "R", "AND", "ANDN", "OR", "ORN",
 "XOR", "XORN", "NOT", "ADD", "SUB", "MUL", "DIV", "MOD", "GT", "GE", "EQ", "NE",
 "LE", "LT", "JMP", "JMPC", "JMPNC", "CAL", "CALC", "CALNC", "RET", "RETC", "RETNC"]


# Keywords for Instruction List and Structured Text
ST_KEYWORDS = ["IF", "THEN", "ELSIF", "ELSE", "END_IF", "CASE", "OF", "END_CASE", 
 "FOR", "TO", "BY", "DO", "END_FOR", "WHILE", "DO", "END_WHILE", "REPEAT", "UNTIL", 
 "END_REPEAT", "EXIT", "RETURN", "NOT", "MOD", "AND", "XOR", "OR"]

 
# All the keywords of IEC
IEC_KEYWORDS = ["E", "TRUE", "FALSE"]
IEC_KEYWORDS.extend([keyword for keyword in POU_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in TYPE_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in VAR_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in CONFIG_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in SFC_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in IL_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in ST_KEYWORDS if keyword not in IEC_KEYWORDS])



"""
take a .csv file and translate it it a "csv_table"
"""            
def csv_file_to_table(file):
    return [ map(string.strip,line.split(';')) for line in file.xreadlines()]

"""
seek into the csv table to a section ( section_name match 1st field )
return the matching row without first field
"""
def find_section(section_name, table):
    fields = [None]
    while(fields[0] != section_name):
        fields = table.pop(0)
    return fields[1:]

"""
extract the standard functions standard parameter names and types...
return a { ParameterName: Type, ...}
"""
def get_standard_funtions_input_variables(table):
    variables = find_section("Standard_functions_variables_types", table)
    standard_funtions_input_variables = {}
    fields = [True,True]
    while(fields[1]):
        fields = table.pop(0)
        variable_from_csv = dict([(champ, val) for champ, val in zip(variables, fields[1:]) if champ!=''])
        standard_funtions_input_variables[variable_from_csv['name']] = variable_from_csv['type']
    return standard_funtions_input_variables
    
"""
translate .csv file input declaration into PLCOpenEditor interessting values
in : "(ANY_NUM, ANY_NUM)" and { ParameterName: Type, ...}
return [("IN1","ANY_NUM","none"),("IN2","ANY_NUM","none")] 
"""
def csv_input_translate(str_decl, variables, base):
    decl = str_decl.replace('(','').replace(')','').replace(' ','').split(',')
    params = []
    
    len_of_not_predifined_variable = len([True for param_type in decl if param_type not in variables])
    
    for param_type in decl:
        if param_type in variables.keys():
            param_name = param_type
            param_type = variables[param_type]
        elif len_of_not_predifined_variable > 1:
            param_name = "IN%d"%base
            base += 1
        else:
            param_name = "IN"
        params.append((param_name, param_type, "none"))
    return params


ANY_T0_ANY_LIST=[
        (("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:
        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]:
             return Format
    
    return None


"""
Returns this kind of declaration for all standard functions

            [{"name" : "Numerical", 'list': [   {   
                'baseinputnumber': 1,
                'comment': 'Addition',
                'extensible': True,
                'inputs': [   ('IN1', 'ANY_NUM', 'none'),
                              ('IN2', 'ANY_NUM', 'none')],
                'name': 'ADD',
                'outputs': [('OUT', 'ANY_NUM', 'none')],
                'type': 'function'}, ...... ] },.....]
"""
def get_standard_funtions(table):
    
    variables = get_standard_funtions_input_variables(table)
    
    fonctions = find_section("Standard_functions_type",table)

    Standard_Functions_Decl = []
    Current_section = None
    
    translate = {
            "extensible" : lambda x: {"yes":True, "no":False}[x],
            "inputs" : lambda x:csv_input_translate(x,variables,baseinputnumber),
            "outputs":lambda x:[("OUT",x,"none")]}
    
    for fields in table:
        if fields[1]:
            # If function section name given
            if fields[0]:
                Current_section = {"name" : fields[0], "list" : []}
                Standard_Functions_Decl.append(Current_section)
                Function_decl_list = []
            if Current_section:
                Function_decl = dict([(champ, val) for champ, val in zip(fonctions, fields[1:]) if champ])
                baseinputnumber = int(Function_decl.get("baseinputnumber",1))
                Function_decl["baseinputnumber"] = baseinputnumber
                for param, value in Function_decl.iteritems():
                    if param in translate:
                        Function_decl[param] = translate[param](value)
                Function_decl["type"] = "function"
                
                if Function_decl["name"].startswith('*') :
                    input_ovrloading_types = GetSubTypes(Function_decl["inputs"][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"]
                funcdeclname = Function_decl["name"].strip('*_')
                fdc = Function_decl["inputs"][:]
                for intype in input_ovrloading_types:
                    if intype != None:
                        Function_decl["inputs"] = []
                        for decl_tpl in fdc:
                            if IsOfType(intype, decl_tpl[1]):
                                Function_decl["inputs"] += [(decl_tpl[0], intype, decl_tpl[2])]
                            else:
                                Function_decl["inputs"] += [(decl_tpl)]
                            
                            if funcdeclname_orig.startswith('*'):
                                funcdeclin = intype + '_' + funcdeclname 
                            else:
                                funcdeclin = funcdeclname
                    else:
                        funcdeclin = funcdeclname
                        
                    for outype in output_types:
                        if outype != None:
                            decl_tpl = Function_decl["outputs"][0]
                            Function_decl["outputs"] = [ (decl_tpl[0] , outype,  decl_tpl[2])]
                            if funcdeclname_orig.endswith('*'):
                                funcdeclout =  funcdeclin + '_' + outype
                            else:
                                funcdeclout =  funcdeclin
                        else:
                            funcdeclout =  funcdeclin
                        Function_decl["name"] = funcdeclout


                        fdecl = Function_decl
                        res = eval(Function_decl["python_eval_c_code_format"])

                        if res != None :
                            # create the copy of decl dict to be appended to section
                            Function_decl_copy = Function_decl.copy()
                            # Have to generate type description in comment with freshly redefined types
                            Function_decl_copy["comment"] += (
                                "\n (" +
                                str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in Function_decl["inputs"]]).strip("[]").replace("'",'') +
                                " ) => (" +
                                str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in Function_decl["outputs"]]).strip("[]").replace("'",'') +
                                " )")
                            Current_section["list"].append(Function_decl_copy)
                            #pp.pprint(Function_decl_copy)
            else:
                raise "First function must be in a category"
    
    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")))))