stage3/remove_forward_dependencies.cc
changeset 959 8bfcc8e62bd6
child 971 8aee27d46208
equal deleted inserted replaced
958:7474d2cd1d6e 959:8bfcc8e62bd6
       
     1 /*
       
     2  *  matiec - a compiler for the programming languages defined in IEC 61131-3
       
     3  *
       
     4  *  Copyright (C) 2014  Mario de Sousa (msousa@fe.up.pt)
       
     5  *
       
     6  *  This program is free software: you can redistribute it and/or modify
       
     7  *  it under the terms of the GNU General Public License as published by
       
     8  *  the Free Software Foundation, either version 3 of the License, or
       
     9  *  (at your option) any later version.
       
    10  *
       
    11  *  This program is distributed in the hope that it will be useful,
       
    12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       
    14  *  GNU General Public License for more details.
       
    15  *
       
    16  *  You should have received a copy of the GNU General Public License
       
    17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
       
    18  *
       
    19  *
       
    20  * This code is made available on the understanding that it will not be
       
    21  * used in safety-critical situations without a full and competent review.
       
    22  */
       
    23 
       
    24 /*
       
    25  * An IEC 61131-3 compiler.
       
    26  *
       
    27  * Based on the
       
    28  * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10)
       
    29  *
       
    30  */
       
    31 
       
    32 /*
       
    33  * Re-oder the POUs in te library so that no forward references occur.
       
    34  * 
       
    35  * Since stage1_2 now suppport POUs that contain references to POUS that are only declared later,
       
    36  * (e.g. a variable of FB1_t is declared, before the FB1_T function block is itself declared!)
       
    37  * we may need to re-order all the POUs in the library so that these forward references do not occur.
       
    38  * 
       
    39  * This utility function will do just that. However, it does not destroy the original abstract syntax 
       
    40  * tree (AST). It instead creates a new re-ordered AST, by instantiating a new library_c object.
       
    41  * This new library_c object will however point to the *same* objects of the original AST, just in 
       
    42  * a new order. 
       
    43  * This means that the new and original AST share all the object instances, and only use a distinct
       
    44  * library_c object!
       
    45  */
       
    46 
       
    47 #include "remove_forward_dependencies.hh"
       
    48 #include "../main.hh" // required for ERROR() and ERROR_MSG() macros.
       
    49 #include "../absyntax_utils/absyntax_utils.hh"
       
    50 
       
    51 
       
    52 
       
    53 
       
    54 
       
    55 #define FIRST_(symbol1, symbol2) (((symbol1)->first_order < (symbol2)->first_order)   ? (symbol1) : (symbol2))
       
    56 #define  LAST_(symbol1, symbol2) (((symbol1)->last_order  > (symbol2)->last_order)    ? (symbol1) : (symbol2))
       
    57 
       
    58 #define FIRST_(symbol1, symbol2) (((symbol1)->first_order < (symbol2)->first_order)   ? (symbol1) : (symbol2))
       
    59 #define  LAST_(symbol1, symbol2) (((symbol1)->last_order  > (symbol2)->last_order)    ? (symbol1) : (symbol2))
       
    60 
       
    61 #define STAGE3_ERROR(error_level, symbol1, symbol2, ...) {                                                                  \
       
    62   if (current_display_error_level >= error_level) {                                                                         \
       
    63     fprintf(stderr, "%s:%d-%d..%d-%d: error: ",                                                                             \
       
    64             FIRST_(symbol1,symbol2)->first_file, FIRST_(symbol1,symbol2)->first_line, FIRST_(symbol1,symbol2)->first_column,\
       
    65                                                  LAST_(symbol1,symbol2) ->last_line,  LAST_(symbol1,symbol2) ->last_column);\
       
    66     fprintf(stderr, __VA_ARGS__);                                                                                           \
       
    67     fprintf(stderr, "\n");                                                                                                  \
       
    68     error_count++;                                                                                                     \
       
    69   }                                                                                                                         \
       
    70 }
       
    71 
       
    72 
       
    73 #define STAGE3_WARNING(symbol1, symbol2, ...) {                                                                             \
       
    74     fprintf(stderr, "%s:%d-%d..%d-%d: warning: ",                                                                           \
       
    75             FIRST_(symbol1,symbol2)->first_file, FIRST_(symbol1,symbol2)->first_line, FIRST_(symbol1,symbol2)->first_column,\
       
    76                                                  LAST_(symbol1,symbol2) ->last_line,  LAST_(symbol1,symbol2) ->last_column);\
       
    77     fprintf(stderr, __VA_ARGS__);                                                                                           \
       
    78     fprintf(stderr, "\n");                                                                                                  \
       
    79     warning_found = true;                                                                                                   \
       
    80 }
       
    81 
       
    82 
       
    83 
       
    84 /* NOTE: We create an independent visitor for this task instead of having this done by the remove_forward_dependencies_c
       
    85  *       because we do not want to handle the ***_pragma_c classes while doing this search.
       
    86  *      (remove_forward_dependencies_c needs to visit those classes when handling all the possible entries in
       
    87  *       library_c, and must have those visitors)
       
    88  * 
       
    89  * NOTE:
       
    90  *      This class could have been written by visiting all the AST objects that could _reference_ a
       
    91  *          - FB type
       
    92  *          - Program type
       
    93  *          - Function type
       
    94  *      and by checking whether those references are in the declared_identifiers list.
       
    95  *      However, one of those objects, the ref_spec_c, may reference an FB type, or any other datatype, so we must have a way
       
    96  *      of knowing what is being referenced in this case. I have opted to introduce a new object type in the AST, the
       
    97  *      poutype_identifier_c, that will be used anywhere in the AST that references either a PROGRAM name or a FB type name
       
    98  *      or a FUNCTION name (previously a simple identifier_c was used!).
       
    99  *      This means that we merely need to visit the new poutype_identifier_c object in this visitor.
       
   100  */
       
   101 class find_forward_dependencies_c: public search_visitor_c {
       
   102   private:
       
   103     identifiers_symbtable_t *declared_identifiers; // list of identifiers already declared by the symbols in the new tree
       
   104   public:
       
   105     find_forward_dependencies_c(identifiers_symbtable_t *declared_identifiers_) {declared_identifiers = declared_identifiers_;}
       
   106   /*******************************************/
       
   107   /* B 1.1 - Letters, digits and identifiers */
       
   108   /*******************************************/
       
   109   // return NULL if the symbol is already in the declared_identifiers symbol table, otherwise return the missing symbol!
       
   110   void *visit(            poutype_identifier_c *symbol)
       
   111     {if (declared_identifiers->find_value(symbol) != declared_identifiers->end_value()) return NULL; else return symbol;}
       
   112 };   /* class find_forward_dependencies_c */
       
   113 
       
   114 
       
   115 
       
   116 
       
   117 /* A class to count the number of POUs (Function, FBs Programs and Configurations) in a library.
       
   118  * This will be used to make sure whether we have copied all the POUs from the original AST (abstract
       
   119  * syntax tree) to the new AST.
       
   120  * Note that we can't simply use the number of 'elements' in the AST, as it may contain unknown/unsupported pragmas.
       
   121  */
       
   122 class pou_count_c: public search_visitor_c {
       
   123   private:
       
   124     static pou_count_c *singleton;
       
   125     long long int count;
       
   126 
       
   127   public:
       
   128     static long long int get_count(library_c *library) {
       
   129       if (NULL == singleton) singleton = new pou_count_c;
       
   130       if (NULL == singleton) ERROR;
       
   131       singleton->count = 0;
       
   132       library->accept(*singleton);
       
   133       return singleton->count;
       
   134     }
       
   135     
       
   136     /**************************************/
       
   137     /* B.1.5 - Program organization units */
       
   138     /**************************************/
       
   139     void *visit(      function_declaration_c *symbol) {count++; return NULL;}
       
   140     void *visit(function_block_declaration_c *symbol) {count++; return NULL;} 
       
   141     void *visit(       program_declaration_c *symbol) {count++; return NULL;} 
       
   142     void *visit( configuration_declaration_c *symbol) {count++; return NULL;} 
       
   143 };   /* class pou_count_c */
       
   144 
       
   145 pou_count_c *pou_count_c::singleton = NULL;
       
   146 symbol_c remove_forward_dependencies_c_null_symbol;
       
   147 
       
   148 
       
   149 
       
   150 
       
   151 
       
   152 
       
   153 
       
   154 
       
   155 /************************************************************/
       
   156 /************************************************************/
       
   157 /******   The main class: Remove Forward Depencies    *******/
       
   158 /************************************************************/
       
   159 /************************************************************/
       
   160 
       
   161 // constructor & destructor
       
   162 remove_forward_dependencies_c:: remove_forward_dependencies_c(void) {
       
   163   find_forward_dependencies      = new find_forward_dependencies_c(&declared_identifiers);
       
   164   current_display_error_level = error_level_default;
       
   165   error_count = 0;
       
   166 }
       
   167 
       
   168 remove_forward_dependencies_c::~remove_forward_dependencies_c(void) {
       
   169   delete find_forward_dependencies;
       
   170 }
       
   171 
       
   172 
       
   173 int remove_forward_dependencies_c::get_error_count(void) {
       
   174   return error_count;
       
   175 }
       
   176 
       
   177 
       
   178 
       
   179 library_c *remove_forward_dependencies_c::create_new_tree(symbol_c *tree) {
       
   180   library_c *old_tree = dynamic_cast<library_c *>(tree);
       
   181   if (NULL == old_tree) ERROR;
       
   182   new_tree = new library_c;
       
   183   *((symbol_c *)new_tree) = *((symbol_c *)tree); // copy any annotations from tree to new_tree;
       
   184   new_tree->clear(); // remove all elements from list.
       
   185   tree->accept(*this);
       
   186   return new_tree;
       
   187 }
       
   188 
       
   189 
       
   190 
       
   191 void *remove_forward_dependencies_c::handle_library_symbol(symbol_c *symbol, symbol_c *name, symbol_c *search1, symbol_c *search2, symbol_c *search3) {
       
   192   if (inserted_symbols.find(symbol) != inserted_symbols.end())                 return NULL; // already previously inserted into new_tree and declared_identifiers. Do not handle again!
       
   193   if ((search1 != NULL) && (search1->accept(*find_forward_dependencies) != NULL)) return NULL; // A forward depency has not yet been satisfied. Wait for a later iteration to try again! 
       
   194   if ((search2 != NULL) && (search2->accept(*find_forward_dependencies) != NULL)) return NULL; // A forward depency has not yet been satisfied. Wait for a later iteration to try again!
       
   195   if ((search3 != NULL) && (search3->accept(*find_forward_dependencies) != NULL)) return NULL; // A forward depency has not yet been satisfied. Wait for a later iteration to try again!
       
   196   /* no forward dependencies found => insert into new AST, and add to the 'defined identifiers' and 'inserted symbol' lists */
       
   197   if (declared_identifiers.find_value(name) == declared_identifiers.end_value())
       
   198       declared_identifiers.insert(name, NULL);  // only add if not yet in the symbol table (an overloaded version of this same POU could have been inderted previously!)
       
   199   inserted_symbols.insert(symbol);
       
   200   new_tree->add_element(current_code_generation_pragma);  
       
   201   new_tree->add_element(symbol);  
       
   202   return NULL;
       
   203 }
       
   204 
       
   205 
       
   206 /* Tell the user that the source code contains a circular dependency */
       
   207 void remove_forward_dependencies_c::print_circ_error(library_c *symbol) {
       
   208   /* Note that we only print Functions and FBs, as Programs and Configurations cannot contain circular references due to syntax rules */
       
   209   /* Note too that circular references in derived datatypes is also not possible due to sytax!                                        */
       
   210   int initial_error_count = error_count;
       
   211   for (int i = 0; i < symbol->n; i++) 
       
   212     if (   (inserted_symbols.find(symbol->elements[i]) == inserted_symbols.end())            // if not copied to new AST
       
   213         &&(  (NULL != dynamic_cast <function_block_declaration_c *>(symbol->elements[i]))    // and (is a FB  
       
   214            ||(NULL != dynamic_cast <      function_declaration_c *>(symbol->elements[i]))))  //      or a Function)
       
   215       STAGE3_ERROR(0, symbol->elements[i], symbol->elements[i], "POU (%s) contains a self-reference and/or belongs in a circular referencing loop", get_datatype_info_c::get_id_str(symbol->elements[i]));
       
   216   if (error_count == initial_error_count) ERROR; // We were unable to determine which POUs contain the circular references!!
       
   217 }
       
   218 
       
   219 
       
   220 /***************************/
       
   221 /* B 0 - Programming Model */
       
   222 /***************************/
       
   223 /* enumvalue_symtable is filled in by enum_declaration_check_c, during stage3 semantic verification, with a list of all enumerated constants declared inside this POU */
       
   224 // SYM_LIST(library_c, enumvalue_symtable_t enumvalue_symtable;)
       
   225 void *remove_forward_dependencies_c::visit(library_c *symbol) {
       
   226   /* this method is the expected entry point for this visitor, and implements the main algorithm of the visitor */
       
   227   
       
   228   /* first insert all the derived datatype declarations, in the same order by which they are delcared in the original AST */
       
   229   /* Since IEC 61131-3 does not allow FBs in arrays or structures, it is actually safe to place all the datatypes before all the POUs! */
       
   230   for (int i = 0; i < symbol->n; i++) 
       
   231     if (NULL != dynamic_cast <data_type_declaration_c *>(symbol->elements[i]))
       
   232       new_tree->add_element(symbol->elements[i]);  
       
   233 
       
   234   /* now do the POUs, in whatever order is necessary to guarantee no forward references. */    
       
   235   long long int old_tree_pou_count = pou_count_c::get_count(symbol);
       
   236     // if no code generation pragma exists before the first entry in the library, the default is to enable code generation.
       
   237   enable_code_generation_pragma_c *default_code_generation_pragma = new enable_code_generation_pragma_c; 
       
   238   int prev_n;
       
   239   cycle_count = 0;
       
   240   do {
       
   241     cycle_count++;
       
   242     prev_n = new_tree->n;
       
   243     current_code_generation_pragma = default_code_generation_pragma;
       
   244     for (int i = 0; i < symbol->n; i++)  symbol->elements[i]->accept(*this);
       
   245   } while (prev_n != new_tree->n); // repeat while new elementns are still being added to the new AST
       
   246   
       
   247   if (old_tree_pou_count != pou_count_c::get_count(new_tree)) 
       
   248     print_circ_error(symbol);
       
   249 
       
   250   return NULL;
       
   251 }
       
   252 
       
   253 
       
   254 /**************************************/
       
   255 /* B.1.5 - Program organization units */
       
   256 /**************************************/
       
   257 /***********************/
       
   258 /* B 1.5.1 - Functions */
       
   259 /***********************/
       
   260 // SYM_REF4(function_declaration_c, derived_function_name, type_name, var_declarations_list, function_body, enumvalue_symtable_t enumvalue_symtable;)
       
   261 void *remove_forward_dependencies_c::visit(function_declaration_c *symbol) 
       
   262   {return handle_library_symbol(symbol, symbol->derived_function_name, symbol->type_name, symbol->var_declarations_list, symbol->function_body);}
       
   263 /*****************************/
       
   264 /* B 1.5.2 - Function Blocks */
       
   265 /*****************************/
       
   266 /*  FUNCTION_BLOCK derived_function_block_name io_OR_other_var_declarations function_block_body END_FUNCTION_BLOCK */
       
   267 // SYM_REF3(function_block_declaration_c, fblock_name, var_declarations, fblock_body, enumvalue_symtable_t enumvalue_symtable;)
       
   268 void *remove_forward_dependencies_c::visit(function_block_declaration_c *symbol) 
       
   269   {return handle_library_symbol(symbol, symbol->fblock_name, symbol->var_declarations, symbol->fblock_body);}
       
   270 /**********************/
       
   271 /* B 1.5.3 - Programs */
       
   272 /**********************/
       
   273 /*  PROGRAM program_type_name program_var_declarations_list function_block_body END_PROGRAM */
       
   274 // SYM_REF3(program_declaration_c, program_type_name, var_declarations, function_block_body, enumvalue_symtable_t enumvalue_symtable;)
       
   275 void *remove_forward_dependencies_c::visit(program_declaration_c *symbol) 
       
   276   {return handle_library_symbol(symbol, symbol->program_type_name, symbol->var_declarations, symbol->function_block_body);}
       
   277 /********************************/
       
   278 /* B 1.7 Configuration elements */
       
   279 /********************************/
       
   280 /* CONFIGURATION configuration_name (...) END_CONFIGURATION */
       
   281 // SYM_REF5(configuration_declaration_c, configuration_name, global_var_declarations, resource_declarations, access_declarations, instance_specific_initializations, enumvalue_symtable_t enumvalue_symtable;)
       
   282 void *remove_forward_dependencies_c::visit(configuration_declaration_c *symbol) 
       
   283   {return handle_library_symbol(symbol, symbol->configuration_name, symbol->global_var_declarations, symbol->resource_declarations, symbol->access_declarations);}
       
   284 /********************/
       
   285 /* 2.1.6 - Pragmas  */
       
   286 /********************/
       
   287 void *remove_forward_dependencies_c::visit(disable_code_generation_pragma_c *symbol) {current_code_generation_pragma = symbol; return NULL;}
       
   288 void *remove_forward_dependencies_c::visit( enable_code_generation_pragma_c *symbol) {current_code_generation_pragma = symbol; return NULL;}
       
   289 /* I have no ideia what this pragma is. Where should we place it in the re-ordered tree? 
       
   290  * Without knowing the semantics of the pragma, it is not possible to hande it correctly.
       
   291  * We therefore print out an error message, and abort!
       
   292  */
       
   293 // TODO: print error message!
       
   294 void *remove_forward_dependencies_c::visit(pragma_c *symbol) {
       
   295   if (1 != cycle_count) return NULL; // only handle unknown pragmas in the first cycle!
       
   296   STAGE3_WARNING(symbol, symbol, "Unrecognized pragma. Including the pragma when using the '-p' command line option for 'allow use of forward references' may result in unwanted behaviour.");
       
   297   new_tree->add_element(symbol);
       
   298   return NULL;
       
   299 }
       
   300 
       
   301 
       
   302 
       
   303