generate_IEC_std.py
author lbessard
Thu, 02 Aug 2007 17:54:42 +0200
changeset 59 af079a11837b
parent 58 39cd981ff242
child 115 017a65259f07
permissions -rw-r--r--
Adding header for files published under LGPL
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#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

"""

 THIS CODE GENARATES C++ CODE FOR IEC2CC COMPILER
 GENERATED CODE IS :
 
function_type_decl.h - the long enumeration of std function types
get_function_type_decl.c - the funct that return enumerated according function name
st_code_gen.c - part of generate_cc_st_c::visit(function_invocation)
                responsible to generate C code for std lib calls
il_code_gen.c - part of generate_cc_il_c::visit(il_function_call)
                responsible to generate C code for std lib calls
search_type_code.c - called by search_expression_type_c::visit(function_invocation) 
                     return type symbol for std function invocation
 
"""

# Get definitions
from plcopen.structures import *

#import pprint
#pp = pprint.PrettyPrinter(indent=4)

matiec_header = """/*
 * (c) 2003 Mario de Sousa
 *
 * Offered to the public under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program 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.
 *
 * This code is made available on the understanding that it will not be
 * used in safety-critical situations without a full and competent review.
 */

/*
 * An IEC 61131-3 IL and ST compiler.
 *
 * Based on the
 * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10)
 *
 */
 
 """

matiec_lesser_header = """/*
 * (c) 2003 Mario de Sousa
 *
 * Offered to the public under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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.
 *
 * This code is made available on the understanding that it will not be
 * used in safety-critical situations without a full and competent review.
 */

/*
 * An IEC 61131-3 IL and ST compiler.
 *
 * Based on the
 * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10)
 *
 */
 
 """

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_NBIT" : "if(search_expression_type->is_nbinary_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))")%{
        "if(search_expression_type->is_same_type(&search_constant_type_c::%(typename)s_type_name, last_type_symbol))")%{
                "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["common_type"] = '");\nlast_type_symbol->accept(*this);\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.indent_right();\n'
                res += 's4o.print("%s\\n" + s4o.indent_spaces);\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" + s4o.indent_spaces);\n'%(code_gen[1])).join(static_param_accept_list)
                code = 's4o.print("%s\\n" + s4o.indent_spaces);\nparam_value->accept(*this);\n'%(code_gen[1])
                end_code = 's4o.print("%s");\ns4o.indent_left();\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 =  matiec_header + """
/****
 * 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 = matiec_header + """
/****
 * 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 = matiec_header + """
/****
 * 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 = matiec_header + """
/****
 * 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 = matiec_header + """
/****
 * 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 standard_function_names[] for inclusion in bizon generated code
"""
standard_function_names = matiec_header + """
/****
 * IEC 61131-3 standard function lib
 * generated code, do not edit by hand
 */

const char *standard_function_names[] = {
"""
for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]:
    standard_function_names += "\""+fname+"\",\n"
standard_function_names += """
/* end of array marker! Do not remove! */
NULL
};

"""

###################################################################
###################################################################
###################################################################
"""
Generate the C implementation of the IEC standard function library.
"""
iec_std_lib_generated = matiec_lesser_header + """
/****
 * 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 path, name, ext in [
        ('stage4/generate_cc','function_type_decl','h'),
        ('stage4/generate_cc','get_function_type_decl','c'),
        ('stage4/generate_cc','st_code_gen','c'),
        ('stage4/generate_cc','il_code_gen','c'),
        ('stage4/generate_cc','search_type_code','c'),
        ('stage1_2','standard_function_names','c'),
        ('lib', 'iec_std_lib_generated','h')
        ]:
    fd = open(os.path.join(sys.argv[1], path, name+'.'+ext),'w')
    fd.write(eval(name))
    fd.close()
    
#print "/* Code to eventually paste in iec_std_lib.h if type hierarchy changed */"
#print "/* you also have to change iec_std_lib.h according to new types        */\n\n"
#print iec_std_lib_generated