plcopen/structures.py
author etisserant
Thu, 10 Jul 2008 18:52:03 +0200
changeset 220 127d1323e5e0
parent 210 17ce08b81775
child 230 45d70748e45a
permissions -rw-r--r--
Added File menu, even in non-solo mode.
#!/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) 2007: 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
#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"]

LOCATIONDATATYPES = {"X" : ["BOOL"],
                     "B" : ["SINT", "USINT", "BYTE", "STRING"],
                     "W" : ["INT", "UINT", "WORD", "WSTRING"],
                     "D" : ["DINT", "UDINT", "REAL", "DWORD"],
                     "L" : ["LINT", "ULINT", "LREAL", "LWORD"]} 

def generate_block(generator, block, body, link, order=False):
    body_type = body.getcontent()["name"]
    name = block.getinstanceName()
    type = block.gettypeName()
    executionOrderId = block.getexecutionOrderId()
    block_infos = GetBlockType(type)
    if block_infos["type"] == "function":
        output_variable = block.outputVariables.getvariable()[0]
        output_name = "%s%d_OUT"%(type, block.getlocalId())
        if not generator.ComputedBlocks.get(block, False) and not order:
            generator.ComputedBlocks[block] = True
            if generator.Interface[-1][0] != "VAR" or generator.Interface[-1][1] or generator.Interface[-1][2] or generator.Interface[-1][3]:
                generator.Interface.append(("VAR", False, False, False, []))
            if output_variable.connectionPointOut in generator.ConnectionTypes:
                generator.Interface[-1][4].append((generator.ConnectionTypes[output_variable.connectionPointOut], output_name, None, None))
            else:
                generator.Interface[-1][4].append(("ANY", output_name, None, None))
            vars = []
            for variable in block.inputVariables.getvariable():
                connections = variable.connectionPointIn.getconnections()
                if connections and len(connections) == 1:
                    if body_type == "FBD" or body_type == "SFC":
                        value = generator.ComputeFBDExpression(body, connections[0], executionOrderId > 0)
                    elif body_type == "LD":
                        paths = generator.GenerateLDPaths(variable.connectionPointIn.getConnections(), body)
                        if len(paths) > 0:
                            paths = tuple(paths)
                        else:
                            paths = paths[0] 
                        value = generator.ComputeLDExpression(paths, True)
                    vars.append(generator.ExtractModifier(variable, value))
            generator.Program += "  %s := %s(%s);\n"%(output_name, type, ", ".join(vars))
        return generator.ExtractModifier(output_variable, output_name)
    elif block_infos["type"] == "functionBlock":
        if not generator.ComputedBlocks.get(block, False) and not order:
            generator.ComputedBlocks[block] = True
            vars = []
            for variable in block.inputVariables.getvariable():
                connections = variable.connectionPointIn.getconnections()
                if connections and len(connections) == 1:
                    parameter = variable.getformalParameter()
                    if body_type == "FBD" or body_type == "SFC":
                        value = generator.ComputeFBDExpression(body, connections[0], executionOrderId > 0)
                    elif body_type == "LD":
                        paths = generator.GenerateLDPaths(variable.connectionPointIn.getconnections(), body)
                        if len(paths) > 0:
                            paths = tuple(paths)
                        else:
                            paths = paths[0] 
                        value = generator.ComputeLDExpression(paths, True)
                    vars.append("%s := %s"%(parameter, generator.ExtractModifier(variable, value)))
            generator.Program += "  %s(%s);\n"%(name, ", ".join(vars))
        if link:
            connectionPoint = link.getposition()[-1]
        else:
            connectionPoint = None
        for variable in block.outputVariables.getvariable():
            blockPointx, blockPointy = variable.connectionPointOut.getrelPositionXY()
            if not connectionPoint or block.getx() + blockPointx == connectionPoint.getx() and block.gety() + blockPointy == connectionPoint.gety():
                return generator.ExtractModifier(variable, "%s.%s"%(name, variable.getformalParameter()))
        raise ValueError, "No output variable found"

def initialise_block(type, name, block = None):
    return [(type, name, None, None)]

#-------------------------------------------------------------------------------
#                        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
    - "generate" : Method that generator will call for generating ST block code
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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block},
                {"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.",
                    "generate" : generate_block, "initialise" : initialise_block}
                ]},
             ]
             
PluginTypes = []

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

def GetBlockType(type, inputs = None):
    for category in BlockTypes + PluginTypes:
        for blocktype in category["list"]:
            if inputs:
                block_inputs = tuple([var_type for name, var_type, modifier in blocktype["inputs"]])
                same_inputs = inputs == block_inputs
            else:
                same_inputs = True
            if blocktype["name"] == type and same_inputs:
                return blocktype
    return None

"""
Function that add a new plugin to the plugin list
"""

def AddPluginBlockList(blocklist):
    PluginTypes.extend(blocklist)
    
def ClearPluginTypes():
    for i in xrange(len(PluginTypes)):
        PluginTypes.pop(0)

#-------------------------------------------------------------------------------
#                           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_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"),
	("BOOL", "ANY_BIT"),
    ("SINT", "ANY_SINT"),
    ("INT", "ANY_SINT"),
    ("DINT", "ANY_SINT"),
    ("LINT", "ANY_SINT"),
    ("USINT", "ANY_UINT"),
    ("UINT", "ANY_UINT"),
    ("UDINT", "ANY_UINT"),
    ("ULINT", "ANY_UINT"),
    ("REAL", "ANY_REAL"),
    ("LREAL", "ANY_REAL"),
    ("TIME", "ANY_MAGNITUDE"),
    ("DATE", "ANY_DATE"),
    ("TOD", "ANY_DATE"),
    ("DT", "ANY_DATE"),
    ("STRING", "ANY_STRING"),
    ("BYTE", "ANY_NBIT"),
    ("WORD", "ANY_NBIT"),
    ("DWORD", "ANY_NBIT"),
    ("LWORD", "ANY_NBIT")
    #("WSTRING", "ANY_STRING") # TODO
]

TypeHierarchy = dict(TypeHierarchy_list)

def ResetTypeHierarchy():
    TypeHierarchy = dict(TypeHierarchy_list)
    
def AddDataTypeHierarchy(name, reference):
    TypeHierarchy[name] = reference

DataTypeRange_list = [
    ("SINT", (-2**7, 2**7 - 1)),
    ("INT", (-2**15, 2**15 - 1)),
    ("DINT", (-2**31, 2**31 - 1)),
    ("LINT", (-2**31, 2**31 - 1)),
    ("USINT", (0, 2**8 - 1)),
    ("UINT", (0, 2**16 - 1)),
    ("UDINT", (0, 2**31 - 1)),
    ("ULINT", (0, 2**31 - 1))
]

DataTypeRange = dict(DataTypeRange_list)

def ResetDataTypeRange():
    DataTypeRange = dict(DataTypeRange_list)
    
def AddDataTypeRange(name, range):
    DataTypeRange[name] = range

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

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

def IsEndType(reference):
    if reference is not None:
        return not reference.startswith("ANY")
    else:
        return True

def GetBaseType(type):
    parent_type = TypeHierarchy[type]
    if parent_type.startswith("ANY"):
        return type
    else:
        return GetBaseType(parent_type)

def GetDataTypeRange(reference):
    while reference is not None:
        if reference in DataTypeRange:
            return DataTypeRange[reference]
        else:
            reference = TypeHierarchy[reference]
    return None

"""
returns list of all types that correspont to the ANY* meta type
"""
def GetSubTypes(reference):
    return [typename for typename, parenttype in TypeHierarchy.items() if not typename.startswith("ANY") and IsOfType(typename, reference)]


EnumeratedDataValues = []

def ResetEnumeratedDataValues():
    EnumeratedDataValues = []
    
def AddEnumeratedDataValues(values):
    EnumeratedDataValues.extend(values)

#-------------------------------------------------------------------------------
#                             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


#-------------------------------------------------------------------------------
#                        Standard functions list generation
#-------------------------------------------------------------------------------


"""
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_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"),
        # 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_NBIT"), "(%(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]:
             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])
                Function_decl["generate"] = generate_block
                Function_decl["initialise"] = lambda x,y:[]
                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('*') 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]
                    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

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)


#-------------------------------------------------------------------------------
#                            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 = ["TRUE", "FALSE", "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 Structured Text
ST_KEYWORDS = ["TRUE", "FALSE", "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])