Changeset 196

Show
Ignore:
Timestamp:
10/23/09 15:15:59 (5 weeks ago)
Author:
lb
Message:

Function and MacroSignature? + MacroDefinitions? attached to the macro reference

Location:
trunk/cpp_analysis/src/xtc/lang/c4
Files:
1 added
8 modified

Legend:

Unmodified
Added
Removed
  • trunk/cpp_analysis/src/xtc/lang/c4/C4Core.rats

    r193 r196  
    5353 
    5454generic Declaration := 
    55    <MacroBased2> ("__extension__":Keyword)? DeclarationSpecifiers SimpleDeclarator id:Identifier &{yyState.isFunctionMacro(toText(id))}  
    56                  void:"(":Symbol FunctionMacroCallParametersList? void:")":Symbol  
     55   <MacroBased2> k:("__extension__":Keyword)? d:DeclarationSpecifiers sId:SimpleDeclarator id:Identifier &{yyState.isFunctionMacro(toText(id))}  
     56                 void:"(":Symbol f:FunctionMacroCallParametersList? void:")":Symbol  
    5757                 l:InitializedDeclaratorList? &{ yyState.isValid(l) }  void:";":Symbol  
    58                  @MacroBased2 
    59  / <MacroBased3> ("__extension__":Keyword)? DeclarationSpecifiers id:Identifier &{yyState.isFunctionMacro(toText(id))}  
    60                  void:"(":Symbol FunctionMacroCallParametersList? void:")":Symbol l:InitializedDeclaratorList?  
     58                 { yyValue = GNode.create("MacroBased2",k, d, sId, id, f, yyState.getMacro(toText(id))); }   
     59                 //@MacroBased2 
     60 / <MacroBased3> mb3_k:("__extension__":Keyword)? mb3_ds:DeclarationSpecifiers id:Identifier &{yyState.isFunctionMacro(toText(id))}  
     61                 void:"(":Symbol f:FunctionMacroCallParametersList? void:")":Symbol l:InitializedDeclaratorList?  
    6162                                 &{ yyState.isValid(l) } void:";":Symbol  
    62                                  @MacroBased3 
    63  / <MacroBased4> ("__extension__":Keyword)? id:Identifier &{yyState.isFunctionMacro(toText(id))}  
    64                  void:"(":Symbol FunctionMacroCallParametersList? void:")":Symbol DeclarationSpecifiers? 
    65                  (void:"=":Symbol Initializer)? void:";":Symbol  
    66                  @MacroBased4     
    67  / <MacroBased5> ("__extension__":Keyword)? DeclarationSpecifier id:Identifier &{yyState.isFunctionMacro(toText(id))}  
    68                  void:"(":Symbol FunctionMacroCallParametersList? void:")":Symbol void:"[":Symbol as:ArraySizeExpression? void:"]":Symbol  
    69                  DeclarationSpecifiers? (void:"=":Symbol Initializer)? void:";":Symbol  
    70                                  @MacroBased5 
    71  / <MacroBased6> ("__extension__":Keyword)? DeclarationSpecifier id:Identifier &{yyState.isFunctionMacro(toText(id))}  
    72                  void:"(":Symbol FunctionMacroCallParametersList? void:")":Symbol DeclarationSpecifiers?  
    73                  (void:"=":Symbol Initializer)? void:";":Symbol  
    74                  @MacroBased6                                           
    75  / <MacroBased7> ("__extension__":Keyword)? DeclarationSpecifier DeclarationSpecifier id:Identifier &{yyState.isFunctionMacro(toText(id))}  
    76                  void:"(":Symbol FunctionMacroCallParametersList? void:")":Symbol  
    77                  DeclarationSpecifiers? (void:"=":Symbol Initializer)? void:";":Symbol  
    78                  @MacroBased7  
    79  / <MacroBased8> ("__extension__":Keyword)? DeclarationSpecifier DeclarationSpecifier id:Identifier &{yyState.isFunctionMacro(toText(id))}  
    80                  DeclarationSpecifiers? (void:"=":Symbol Initializer)?  void:";":Symbol  
    81                                  @MacroBased8                                            
     63                                 { yyValue = yyState.annotate(GNode.create("MacroBased3", mb3_k, mb3_ds, id, f, l, yyState.getMacro(toText(id)))); }   
     64                 //@MacroBased3 
     65 / <MacroBased4> k:("__extension__":Keyword)? id:Identifier &{yyState.isFunctionMacro(toText(id))}  
     66                 void:"(":Symbol f:FunctionMacroCallParametersList? void:")":Symbol d:DeclarationSpecifiers? 
     67                 init:(void:"=":Symbol Initializer)? void:";":Symbol  
     68                 { yyValue = yyState.annotate(GNode.create("MacroBased4",k, id, f, d, init, yyState.getMacro(toText(id)))); }   
     69                 //@MacroBased4  {System.out.println("TEST");}  
     70 / <MacroBased5> mb5_k:("__extension__":Keyword)? mb5_ds:DeclarationSpecifier id:Identifier &{yyState.isFunctionMacro(toText(id))}  
     71                 void:"(":Symbol f:FunctionMacroCallParametersList? void:")":Symbol void:"[":Symbol as:ArraySizeExpression? void:"]":Symbol  
     72                 mb5_ds2:DeclarationSpecifiers? init:(void:"=":Symbol Initializer)? void:";":Symbol  
     73                                 { yyValue = yyState.annotate(GNode.create("MacroBased5", mb5_ds, id, f, as, mb5_ds2, init, yyState.getMacro(toText(id)))); }   
     74                 //@MacroBased5 
     75 / <MacroBased6> mb6_k:("__extension__":Keyword)? d:DeclarationSpecifier id:Identifier &{yyState.isFunctionMacro(toText(id))}  
     76                 void:"(":Symbol f:FunctionMacroCallParametersList? void:")":Symbol ds:DeclarationSpecifiers?  
     77                 init:(void:"=":Symbol Initializer)? void:";":Symbol  
     78                 { yyValue = GNode.create("MacroBased6",mb6_k, d, id, f, ds, init, yyState.getMacro(toText(id))); }   
     79                 //@MacroBased6                                           
     80 / <MacroBased7> mb7_k:("__extension__":Keyword)? ds1:DeclarationSpecifier ds2:DeclarationSpecifier id:Identifier &{yyState.isFunctionMacro(toText(id))}  
     81                 void:"(":Symbol f:FunctionMacroCallParametersList? void:")":Symbol  
     82                 ds3:DeclarationSpecifiers? init:(void:"=":Symbol Initializer)? void:";":Symbol  
     83                 { yyValue = yyState.annotate(GNode.create("MacroBased7",mb7_k, ds1, ds2, id, f, ds3, init, yyState.getMacro(toText(id)))); }   
     84                 //@MacroBased7  
     85 / <MacroBased8> mb8_k:("__extension__":Keyword)? mb8_ds1:DeclarationSpecifier mb8_ds2:DeclarationSpecifier id:Identifier &{yyState.isFunctionMacro(toText(id))}  
     86                 ds3:DeclarationSpecifiers? init:(void:"=":Symbol Initializer)?  void:";":Symbol  
     87                                 { yyValue = yyState.annotate(GNode.create("MacroBased8",mb8_k, mb8_ds1, mb8_ds2, id, ds3, init, yyState.getMacro(toText(id)))); }   
     88                 //@MacroBased8                                            
    8289 / <MacroBased9> ("__extension__":Keyword)? DeclarationSpecifier MacroFunctionExpression void:";":Symbol  
    8390                                 @MacroBased9 
    84  / <MacroBased10> ("__extension__":Keyword)? DeclarationSpecifier void:"*":Symbol id:Identifier &{yyState.isFunctionMacro(toText(id))}  
    85                   void:"(":Symbol FunctionMacroCallParametersList? void:")":Symbol DeclarationSpecifiers? (void:"=":Symbol Initializer)?  void:";":Symbol  
    86                                   @MacroBased10 
     91 / <MacroBased10> k:("__extension__":Keyword)? ds1:DeclarationSpecifier void:"*":Symbol id:Identifier &{yyState.isFunctionMacro(toText(id))}  
     92                  void:"(":Symbol f:FunctionMacroCallParametersList? void:")":Symbol ds2:DeclarationSpecifiers? init:(void:"=":Symbol Initializer)?  void:";":Symbol  
     93                                 { yyValue = yyState.annotate(GNode.create("MacroBased10",k, ds1, id, f, ds2, init, yyState.getMacro(toText(id)))); }   
     94                 //@MacroBased10 
    8795 / <RegularWithIfSection>  ("__extension__":Keyword)? DeclarationSpecifiers AttributeSpecifierList?  
    8896                           Declarator SimpleAssemblyExpression? AttributeSpecifierList? void:"=":Symbol IfSection   
     
    384392generic FunctionMacroCallStatement = 
    385393  id:Identifier &{yyState.isFunctionMacro(toText(id))} void:"(":Symbol f:FunctionMacroCallParametersList?  
    386     void:")":Symbol CompoundStatement? 
     394    void:")":Symbol c:CompoundStatement?  
     395    { yyValue = GNode.create("FunctionMacroCallStatement", id, f, c, yyState.getMacro(toText(id))); }  
    387396; 
    388397 
     
    410419 
    411420generic MacroFunctionExpression =  
    412         id:Identifier &{yyState.isFunctionMacro(toText(id))} void:"(":Symbol FunctionMacroCallParametersList? 
    413         void:")":Symbol  
     421        id:Identifier &{yyState.isFunctionMacro(toText(id))} void:"(":Symbol f:FunctionMacroCallParametersList? 
     422        void:")":Symbol { yyValue = GNode.create("MacroFunctionExpression", id, f, yyState.getMacro(toText(id))); } 
    414423; 
    415424 
     
    962971                   { 
    963972                      Node tmpExp = exp.strip(); 
    964               if (tmpExp.getName() == "IfGroupAdditiveExpression"       ||  
    965                          tmpExp.getName() == "IfGroupMultiplicativeExpression" ||  
    966                          tmpExp.getName() == "IfGroupBinaryExpression"         || 
    967                          tmpExp.getName() == "IntegerConstant"                 || 
    968                  tmpExp.getName() == "FunctionMacroCallExpression" ) { 
     973              if (tmpExp.getName().equals("IfGroupAdditiveExpression")       ||  
     974                         tmpExp.getName().equals("IfGroupMultiplicativeExpression") ||  
     975                         tmpExp.getName().equals("IfGroupBinaryExpression")         || 
     976                         tmpExp.getName().equals("IntegerConstant")                 || 
     977                 tmpExp.getName().equals("FunctionMacroCallExpression") ) { 
    969978                        yyState.compute(tmpExp); 
    970979                            yyState.setDefined(yyState.isTrue(yyState.getTmpCondValue())); 
  • trunk/cpp_analysis/src/xtc/lang/c4/C4Extractor.java

    r193 r196  
    3030 
    3131 
    32   /** The Debug extraction Flag **/ 
    33   private boolean DBG_EXTRACT = false; 
    34   /** The feature to create **/ 
    35   private String featureName; 
    36    
    37   /** The Configuration option to extract **/ 
    38   private String configOption; 
    39   /** The list of nodes  marked as to be extracted by the CPP Analyzer **/ 
    40   private ArrayList<C4Extractable> toExtract; 
    41  
    42   /** The original Tree before any extraction **/ 
    43   private Node tree;  
    44   /** The new Tree with everything extracted **/ 
    45   private Node newTree; 
    46   /** The name of the top level file to be extracted **/ 
    47   /** We do not extract anything from the included header files **/ 
    48   private String topLevel; 
    49    
    50   /** The collection of functionDefinitions extracted from the analysis 
    51    */ 
    52   private Map<String, GNode> functionDefinitions; 
    53  
    54   /** The collection of functionDefinitions after all the modification 
    55    *  populated during the extraction process 
    56    */ 
    57   private Map<String, GNode> modifiedFunctionDefinitions; 
    58  
    59   private Node father; 
    60  
    61   public C4Extractor(String featureName, String optExtract, ArrayList<C4Extractable> toExtract, Node unit, String fileName, Map<String, GNode> functionDefinitions ) { 
    62     this.featureName = featureName;  
    63     configOption   = optExtract; 
    64     this.toExtract      = toExtract; 
    65     tree           = unit; 
    66     topLevel       = fileName; 
    67     this.functionDefinitions = functionDefinitions; 
    68     modifiedFunctionDefinitions = new HashMap<String, GNode> (); 
    69   } 
    70  
    71  
    72   static Node build(Formatting n, HashMap<Integer, Object> newChildren) { 
    73     Formatting result = null ; 
    74     try { 
    75       if(n.size() != newChildren.size()) { 
    76         return GNode.create("toPurge", n); 
    77       } 
    78       if(n.getName().contains("After1")) { 
    79         result = Formatting.after1((Node) newChildren.get(new Integer(0)), newChildren.get(new Integer(1))); 
    80       } else if(n.getName().contains("Before1")) { 
    81         result = Formatting.before1(newChildren.get(new Integer(0)), (Node) newChildren.get(new Integer(1))); 
    82       } else if(n.getName().contains("Round1")) { 
    83         result = Formatting.round1(newChildren.get(new Integer(0)), (Node) newChildren.get(new Integer(1)), newChildren.get(new Integer(2))); 
    84       } else if(n.getName().contains("RoundN")) { 
    85         result = Formatting.variable(); 
    86  
    87         for(int index = 0; index < newChildren.size(); index++) { 
    88           result.add(index, newChildren.get(new Integer(index))); 
    89         } 
    90  
    91       } 
    92       else { 
    93         result = null; 
    94       } 
    95     } catch (Exception ex) { 
    96       System.out.println("\n\n######EXCEPTION \n\n" + ex.getMessage()); 
    97       System.out.println("FORMATTING " + n ); 
    98       System.out.println("NEW CHILDREN " + newChildren); 
    99  
    100       System.exit(-1); 
    101       result = null; 
    102     } 
    103  
    104     return result; 
    105   } 
    106  
    107   private Node extractVisitor(Node n) { 
    108     //Node modified = GNode.create((GNode)n); 
    109  
    110     //When we remove some children, we have to change the index. 
    111     //the modifiedIndex is aware of the updated size. 
    112     int modifiedIndex = 0; 
    113     ArrayList<Integer> toRemove = new ArrayList<Integer>(); 
    114     HashMap<Integer, Object> newChildren = new HashMap<Integer, Object>(); 
    115     String name = n.getName(); 
    116  
    117     if(0 == n.size()) { 
    118       if(DBG_EXTRACT) 
    119         System.out.println("SIZE ZERO... We return the same node " + n); 
    120       return n; 
    121     } 
    122  
    123     for(int i = 0; i< n.size(); i++) {  
    124       if(n.get(i) instanceof Node) { 
    125         Integer index = new Integer(i); 
    126         Node child = (Node) n.get(i); 
    127  
    128         if(isToBeExtracted(child)) { 
    129           if(DBG_EXTRACT) 
    130             System.out.println("We are going to remove child number : " + index); 
    131  
    132           father = n; 
    133           toRemove.add(index); 
    134  
    135         } else {  
    136  
    137           Node dispatched = (Node) dispatch(child); 
    138  
    139           if(DBG_EXTRACT) 
    140             System.out.println("DISPATCHED " + dispatched + "\nCHILD " + child); 
    141  
    142           if(dispatched != null) { 
    143  
    144             if(!dispatched.getName().equals("toPurge")) { 
    145               newChildren.put(new Integer(modifiedIndex), dispatched); 
    146               modifiedIndex++; 
    147             } else { 
    148               if(DBG_EXTRACT) 
    149                 System.out.println("DISPATCHED " + dispatched); 
    150             } 
    151           } else { 
    152             if(DBG_EXTRACT) 
    153               System.out.println("========= DISPATCHED IS NULL ===========>>>>>> " + dispatched); 
    154           } 
    155  
    156         } 
    157  
    158  
    159       } else if(n.get(i) instanceof String) { 
    160         newChildren.put(new Integer(modifiedIndex), n.getString(i)); 
    161  
    162         modifiedIndex++; 
    163  
    164       } else if(null == n.get(i)){ 
    165         newChildren.put(new Integer(modifiedIndex), null); 
    166         modifiedIndex++; 
    167       } else { 
    168         newChildren.put(new Integer(modifiedIndex), n.get(i)); 
    169         modifiedIndex++; 
    170       } 
    171     } 
    172  
    173     if(newChildren.size() == 0) { 
    174       return GNode.create("toPurge", n); 
    175     } 
    176  
    177     //The new node which is going to be returned 
    178     Node modified = null; 
    179  
    180     if(n instanceof GNode) { 
    181       modified =  GNode.create(name, newChildren.size()); 
    182  
    183       //Creation of the new Node 
    184       for (int k = 0; k < newChildren.size(); k++) { 
    185         Integer bigK = new Integer(k); 
    186         modified.add(k, newChildren.get(bigK)); 
    187       } 
    188  
    189       if (name == "FunctionDefinition") { 
    190           //We look for the name of this function 
    191           if (functionDefinitions.containsValue(n)) { 
    192             for (String funcName: functionDefinitions.keySet()) { 
    193                 if(functionDefinitions.get(funcName) == n) { 
    194                     modifiedFunctionDefinitions.put(funcName, (GNode)modified); 
    195                 } 
    196             } 
    197          } 
    198       } 
    199  
    200     } 
    201     else if( (n instanceof Formatting)) { 
    202       // 
    203       Node f = build((Formatting) n, newChildren); 
    204       return f; 
    205  
    206     } else if(n instanceof Token) { 
    207       return n; 
    208     } else { 
    209       if(DBG_EXTRACT) 
    210         System.out.println("N KIND " + n.getName()); 
    211     } 
    212  
    213     if(modified  == null) { 
    214       System.exit(-1); 
    215     } 
    216  
    217     return modified; 
    218  
    219   } 
    220  
    221   public Object visit(Annotation a) { 
    222     return extractVisitor(a); 
    223   } 
    224  
    225   public Node visit(Node n) { 
    226     return extractVisitor(n); 
    227   } 
    228  
    229   public void extract() { 
    230     newTree = (Node) dispatch(tree); 
    231  
    232     if(DBG_EXTRACT) { 
    233     //console Printer 
    234       Printer console = new Printer(new BufferedWriter(new OutputStreamWriter(System.out))); 
    235       System.out.println("\n\nPARSE TREE BEFORE EXTRACTION"); 
    236       console.format(tree, false).pln().flush(); 
    237       System.out.println("\n\nAFTER EXTRACTION"); 
    238       console.format(newTree, false).pln().flush(); 
    239  
    240       System.out.println("\n\n###EXTRACTION RESULT#####\n"); 
    241       System.out.println("PARSETREE PRINTER\n\n"); 
    242       new ParseTreePrinter(console).dispatch(tree); 
    243       console.flush(); 
    244       System.out.println("PARSENEWTREE PRINTER\n\n"); 
    245       new C4ParseTreePrinter(console).dispatch(newTree); 
    246       console.flush(); 
    247       System.out.println("\n#######\n"); 
    248     } 
    249     try  { 
    250     
    251     Printer result_file = new Printer(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("__extract_"+topLevel.substring(topLevel.lastIndexOf("/") + 1 ))))); 
    252     new C4ParseTreePrinter(result_file).dispatch(newTree); 
    253     result_file.flush(); 
    254      
    255     } catch(FileNotFoundException fne) { 
    256         System.out.println( "FILE: " + "__extract_"+topLevel.substring(topLevel.lastIndexOf("/") + 1 ) + " not found...");  
    257         fne.printStackTrace(); 
    258     } 
    259    
    260     //Weaving 
    261     weave(newTree); 
    262       
    263    
    264   } 
    265  
    266  
    267  
    268   private ArrayList<C4Extractable> lookupToWeave(String funcName) { 
    269     ArrayList<C4Extractable> toWeave = new ArrayList<C4Extractable>(); 
    270      
    271     for(C4Extractable item : toExtract) { 
    272         if(item.getFuncName().equals(funcName)) { 
    273             toWeave.add(item); 
    274         } 
    275     } 
    276     return toWeave; 
    277   } 
    278  
    279  
    280   private void weave(Node newTree) { 
    281       Printer console = new Printer(new BufferedWriter(new OutputStreamWriter(System.out)));  
    282       new ParseTreePrinter(console).dispatch(tree); 
    283       System.out.println("\n\nABeforeEXTRACTION"); 
    284       console.format(newTree, false).pln().flush(); 
    285  
    286   
    287       new Visitor() { 
    288         public void visitFunctionDefinition(GNode n ) { 
    289           if (modifiedFunctionDefinitions.containsValue(n)) { 
    290             for (String funcName: modifiedFunctionDefinitions.keySet()) { 
    291                 if(modifiedFunctionDefinitions.get(funcName) == n) { 
    292                     ArrayList<C4Extractable> toWeave = lookupToWeave(funcName);  
    293                     n.getGeneric(5).add(0,blockWrapping(toWeave)); 
    294                 } 
    295             } 
    296          } 
    297   
    298         } 
    299  
    300         public void visit(Node n) { 
    301             for(int i=0; i < n.size(); i++) { 
    302                 if(n.get(i) instanceof Node) { 
    303                     dispatch(n.getNode(i)); 
    304                 } 
    305             } 
    306         } 
    307  
    308       }.dispatch(newTree); 
    309        
    310        
    311  
    312       System.out.println("AFTER WEAVING PRINTER\n\n"); 
    313       new C4ParseTreePrinter(console).dispatch(newTree); 
    314       console.flush(); 
    315       System.out.println("\n#######\n"); 
    316   
    317  
    318     } 
    319  
    320   private boolean isToBeExtracted(Node n) { 
    321         for(C4Extractable toBeExtracted : toExtract) { 
    322            if(toBeExtracted.getGNodeToExtract() == n) { 
    323                return true; 
    324             } 
    325         } 
    326          
    327         return false; 
    328     } 
    329  
    330   private Node blockWrapping(ArrayList<C4Extractable> toWeave) { 
    331     GNode tmpGNodeBefore = GNode.create("RawFeatureBefore"); 
    332     GNode tmpGNodeAfter = GNode.create("RawFeatureAfter"); 
    333      
    334     for(C4Extractable item: toWeave) { 
    335  
    336         if(item.getKind().equals("before")) 
    337             tmpGNodeBefore.add(item.getGNodeToExtract()); 
    338         else if(item.getKind().equals("after")) 
    339             tmpGNodeAfter.add(item.getGNodeToExtract()); 
    340   
    341     }  
    342  
    343     GNode featureBlock = GNode.create("FeatureBlockStatement"); 
    344      
    345     if(tmpGNodeBefore.size() > 0) {  
    346         Formatting roundBefore = Formatting.round1(new Token("_before_" + featureName + " { \n\t"), tmpGNodeBefore,new Token("\n    }\n")); 
    347         featureBlock.add(roundBefore); 
    348     } 
    349     if(tmpGNodeAfter.size() > 0) { 
    350     Formatting roundAfter = Formatting.round1(new Token("_after_" + featureName + " { \n\t"), tmpGNodeAfter,new Token("\n    }\n")); 
    351         featureBlock.add(roundAfter); 
    352     } 
    353  
    354     return featureBlock; 
    355  
    356   } 
     32        /** The Debug extraction Flag **/ 
     33        private boolean DBG_EXTRACT = false; 
     34        /** The feature to create **/ 
     35        private String featureName; 
     36 
     37        /** The Configuration option to extract **/ 
     38        private String configOption; 
     39        /** The list of nodes  marked as to be extracted by the CPP Analyzer **/ 
     40        private ArrayList<C4Extractable> toExtract; 
     41 
     42        /** The original Tree before any extraction **/ 
     43        private Node tree;  
     44        /** The new Tree with everything extracted **/ 
     45        private Node newTree; 
     46        /** The name of the top level file to be extracted **/ 
     47        /** We do not extract anything from the included header files **/ 
     48        private String topLevel; 
     49 
     50        /** The collection of functionDefinitions extracted from the analysis 
     51         */ 
     52        private Map<String, GNode> functionDefinitions; 
     53 
     54        /** The collection of functionDefinitions after all the modification 
     55         *  populated during the extraction process 
     56         */ 
     57        private Map<String, GNode> modifiedFunctionDefinitions; 
     58 
     59        private Node father; 
     60 
     61        public C4Extractor(String featureName, String optExtract, ArrayList<C4Extractable> toExtract, Node unit, String fileName, Map<String, GNode> functionDefinitions ) { 
     62                this.featureName = featureName;  
     63                configOption   = optExtract; 
     64                this.toExtract      = toExtract; 
     65                tree           = unit; 
     66                topLevel       = fileName; 
     67                this.functionDefinitions = functionDefinitions; 
     68                modifiedFunctionDefinitions = new HashMap<String, GNode> (); 
     69        } 
     70 
     71 
     72        static Node build(Formatting n, HashMap<Integer, Object> newChildren) { 
     73                Formatting result = null ; 
     74                try { 
     75                        if(n.size() != newChildren.size()) { 
     76                                return GNode.create("toPurge", n); 
     77                        } 
     78                        if(n.getName().contains("After1")) { 
     79                                result = Formatting.after1((Node) newChildren.get(new Integer(0)), newChildren.get(new Integer(1))); 
     80                        } else if(n.getName().contains("Before1")) { 
     81                                result = Formatting.before1(newChildren.get(new Integer(0)), (Node) newChildren.get(new Integer(1))); 
     82                        } else if(n.getName().contains("Round1")) { 
     83                                result = Formatting.round1(newChildren.get(new Integer(0)), (Node) newChildren.get(new Integer(1)), newChildren.get(new Integer(2))); 
     84                        } else if(n.getName().contains("RoundN")) { 
     85                                result = Formatting.variable(); 
     86 
     87                                for(int index = 0; index < newChildren.size(); index++) { 
     88                                        result.add(index, newChildren.get(new Integer(index))); 
     89                                } 
     90 
     91                        } 
     92                        else { 
     93                                result = null; 
     94                        } 
     95                } catch (Exception ex) { 
     96                        System.out.println("\n\n######EXCEPTION \n\n" + ex.getMessage()); 
     97                        System.out.println("FORMATTING " + n ); 
     98                        System.out.println("NEW CHILDREN " + newChildren); 
     99 
     100                        System.exit(-1); 
     101                        result = null; 
     102                } 
     103 
     104                return result; 
     105        } 
     106 
     107        private Node extractVisitor(Node n) { 
     108                //Node modified = GNode.create((GNode)n); 
     109 
     110                //When we remove some children, we have to change the index. 
     111                //the modifiedIndex is aware of the updated size. 
     112                 
     113                int modifiedIndex = 0; 
     114                ArrayList<Integer> toRemove = new ArrayList<Integer>(); 
     115                HashMap<Integer, Object> newChildren = new HashMap<Integer, Object>(); 
     116                String name = n.getName(); 
     117 
     118                if(0 == n.size()) { 
     119                        if(DBG_EXTRACT) 
     120                                System.out.println("SIZE ZERO... We return the same node " + n); 
     121                        return n; 
     122                } 
     123 
     124                for(int i = 0; i< n.size(); i++) {  
     125                        if(n.get(i) instanceof Node) { 
     126                                Integer index = new Integer(i); 
     127                                Node child = (Node) n.get(i); 
     128 
     129                                if(isToBeExtracted(child)) { 
     130 
     131                                        if(DBG_EXTRACT) 
     132                                                System.out.println("We are going to remove child number : " + index); 
     133 
     134                                        father = n; 
     135                                        toRemove.add(index); 
     136 
     137                                } else {  
     138 
     139                                        Node dispatched = (Node) dispatch(child); 
     140 
     141                                        if(DBG_EXTRACT) 
     142                                                System.out.println("DISPATCHED " + dispatched + "\nCHILD " + child); 
     143 
     144                                        if(dispatched != null) { 
     145 
     146                                                if(!dispatched.getName().equals("toPurge")) { 
     147                                                        newChildren.put(new Integer(modifiedIndex), dispatched); 
     148                                                        modifiedIndex++; 
     149                                                } else { 
     150                                                        if(DBG_EXTRACT) 
     151                                                                System.out.println("DISPATCHED " + dispatched); 
     152                                                } 
     153                                        } else { 
     154                                                if(DBG_EXTRACT) 
     155                                                        System.out.println("========= DISPATCHED IS NULL ===========>>>>>> " + dispatched); 
     156                                        } 
     157 
     158                                } 
     159 
     160 
     161                        } else if(n.get(i) instanceof String) { 
     162                                newChildren.put(new Integer(modifiedIndex), n.getString(i)); 
     163 
     164                                modifiedIndex++; 
     165 
     166                        } else if(null == n.get(i)) { 
     167                                newChildren.put(new Integer(modifiedIndex), null); 
     168                                modifiedIndex++; 
     169                        } else { 
     170                                newChildren.put(new Integer(modifiedIndex), n.get(i)); 
     171                                modifiedIndex++; 
     172                        } 
     173                } 
     174 
     175                if(newChildren.size() == 0) { 
     176                        return GNode.create("toPurge", n); 
     177                } 
     178 
     179                //The new node which is going to be returned 
     180                Node modified = null; 
     181 
     182                if(n instanceof GNode) { 
     183                        modified =  GNode.create(name, newChildren.size()); 
     184 
     185                        //Creation of the new Node 
     186                        for (int k = 0; k < newChildren.size(); k++) { 
     187                                Integer bigK = new Integer(k); 
     188                                modified.add(k, newChildren.get(bigK)); 
     189                        } 
     190 
     191                        if (name.equals("FunctionDefinition")) { 
     192                                //We look for the name of this function 
     193                                if (functionDefinitions.containsValue(n)) { 
     194                                        for (String funcName: functionDefinitions.keySet()) { 
     195                                                if(functionDefinitions.get(funcName) == n) { 
     196                                                        modifiedFunctionDefinitions.put(funcName, (GNode)modified); 
     197                                                } 
     198                                        } 
     199                                } 
     200                        } 
     201 
     202                } 
     203                else if( (n instanceof Formatting)) { 
     204                        // 
     205                        Node f = build((Formatting) n, newChildren); 
     206                        return f; 
     207 
     208                } else if(n instanceof Token) { 
     209                        return n; 
     210                } else { 
     211                        if(DBG_EXTRACT) 
     212                                System.out.println("N KIND " + n.getName()); 
     213                } 
     214 
     215                if(modified  == null) { 
     216                        System.exit(-1); 
     217                } 
     218 
     219                return modified; 
     220 
     221        } 
     222 
     223        public Object visit(Annotation a) { 
     224                return extractVisitor(a); 
     225        } 
     226 
     227        public Node visit(Node n) { 
     228                return extractVisitor(n); 
     229        } 
     230 
     231        public void extract() { 
     232                newTree = (Node) dispatch(tree); 
     233 
     234                if(DBG_EXTRACT) { 
     235                        //console Printer 
     236                        Printer console = new Printer(new BufferedWriter(new OutputStreamWriter(System.out))); 
     237                        System.out.println("\n\nPARSE TREE BEFORE EXTRACTION"); 
     238                        console.format(tree, false).pln().flush(); 
     239                        System.out.println("\n\nAFTER EXTRACTION"); 
     240                        console.format(newTree, false).pln().flush(); 
     241 
     242                        System.out.println("\n\n###EXTRACTION RESULT#####\n"); 
     243                        System.out.println("PARSETREE PRINTER\n\n"); 
     244                        new ParseTreePrinter(console).dispatch(tree); 
     245                        console.flush(); 
     246                        System.out.println("PARSENEWTREE PRINTER\n\n"); 
     247                        new C4ParseTreePrinter(console).dispatch(newTree); 
     248                        console.flush(); 
     249                        System.out.println("\n#######\n"); 
     250                } 
     251                try  { 
     252 
     253                        Printer result_file = new Printer(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("__extract_"+topLevel.substring(topLevel.lastIndexOf("/") + 1 ))))); 
     254                        new C4ParseTreePrinter(result_file).dispatch(newTree); 
     255                        result_file.flush(); 
     256 
     257                } catch(FileNotFoundException fne) { 
     258                        System.out.println( "FILE: " + "__extract_"+topLevel.substring(topLevel.lastIndexOf("/") + 1 ) + " not found...");  
     259                        fne.printStackTrace(); 
     260                } 
     261 
     262                //Weaving 
     263                weave(newTree); 
     264 
     265 
     266        } 
     267 
     268 
     269 
     270        private ArrayList<C4Extractable> lookupToWeave(String funcName) { 
     271                ArrayList<C4Extractable> toWeave = new ArrayList<C4Extractable>(); 
     272                 
     273                for(C4Extractable item : toExtract) { 
     274                        if(item.getFuncName().equals(funcName)) { 
     275                                toWeave.add(item); 
     276                        } 
     277                } 
     278                 
     279                return toWeave; 
     280        } 
     281 
     282 
     283        private void weave(Node newTree) { 
     284                Printer console = new Printer(new BufferedWriter(new OutputStreamWriter(System.out)));  
     285                new ParseTreePrinter(console).dispatch(tree); 
     286                //System.out.println("\n\nBEFORE WEAVING"); 
     287                //console.format(newTree, false).pln().flush(); 
     288 
     289 
     290                new Visitor() { 
     291                        public void visitFunctionDefinition(GNode n ) { 
     292                                if (modifiedFunctionDefinitions.containsValue(n)) { 
     293                                        for (String funcName: modifiedFunctionDefinitions.keySet()) { 
     294                                                if(modifiedFunctionDefinitions.get(funcName) == n) { 
     295                                                        ArrayList<C4Extractable> toWeave = lookupToWeave(funcName);  
     296                                                        n.getGeneric(5).add(0,blockWrapping(toWeave)); 
     297                                                } 
     298                                        } 
     299                                } 
     300 
     301                        } 
     302 
     303                        public void visit(Node n) { 
     304                                for(int i=0; i < n.size(); i++) { 
     305                                        if(n.get(i) instanceof Node) { 
     306                                                dispatch(n.getNode(i)); 
     307                                        } 
     308                                } 
     309                        } 
     310 
     311                }.dispatch(newTree); 
     312 
     313 
     314 
     315                System.out.println("\nAFTER WEAVING\n\n"); 
     316                console.format(newTree, false).pln().flush(); 
     317                System.out.println("\nAfterC4ParseTree\n"); 
     318                new C4ParseTreePrinter(console).dispatch(newTree); 
     319                console.flush(); 
     320                System.out.println("\n#######\n"); 
     321 
     322 
     323        } 
     324 
     325        private boolean isToBeExtracted(Node n) { 
     326                for(C4Extractable toBeExtracted : toExtract) { 
     327                        if(toBeExtracted.getGNodeToExtract() == n) { 
     328                                return true; 
     329                        } 
     330                } 
     331 
     332                return false; 
     333        } 
     334 
     335        private Node blockWrapping(ArrayList<C4Extractable> toWeave) { 
     336                GNode tmpGNodeBefore = GNode.create("RawFeatureBefore"); 
     337                GNode tmpGNodeAfter = GNode.create("RawFeatureAfter"); 
     338 
     339                for(C4Extractable item: toWeave) { 
     340 
     341                        if(item.getKind().equals("before")) 
     342                                tmpGNodeBefore.add(item.getGNodeToExtract()); 
     343                        else if(item.getKind().equals("after")) 
     344                                tmpGNodeAfter.add(item.getGNodeToExtract()); 
     345 
     346                }  
     347 
     348                GNode featureBlock = GNode.create("FeatureBlockStatement"); 
     349 
     350                if(tmpGNodeBefore.size() > 0) {  
     351                        Formatting roundBefore = Formatting.round1(new Token("_before_" + featureName + " { \n\t"), tmpGNodeBefore,new Token("\n    }\n\t\n")); 
     352                        featureBlock.add(roundBefore); 
     353                } 
     354 
     355                if(tmpGNodeAfter.size() > 0) { 
     356                        Formatting roundAfter = Formatting.round1(new Token("_after_" + featureName + " { \n\t"), tmpGNodeAfter,new Token("\n    }\n")); 
     357                        featureBlock.add(roundAfter); 
     358                } 
     359 
     360                return featureBlock; 
     361 
     362        } 
    357363} 
  • trunk/cpp_analysis/src/xtc/lang/c4/C4MacrosManager.java

    r193 r196  
    2525        private Map<String, ArrayList<Node>> oldDefinitionsMacros; 
    2626         
    27         /** A map of the current definition of each macro defined **/ 
    28         private Map<String, Node> currentDefinitionMacros; 
    29         private Map<String, Integer> currentDefinitionIndex; 
    30  
    3127        /** To remove all the macros defined in the previous branch...*/ 
    3228        private ArrayList<ArrayList <String>> branchMacros; 
     
    5753                this.macro_keyword_parents = new ArrayList<ArrayList<String>>(); 
    5854                this.keywords_toFlush = new ArrayList<ArrayList<String>>(); 
    59                 this.branchMacros.add(lastBranchMacros); 
     55                 
     56        this.branchMacros.add(lastBranchMacros); 
    6057        } 
    6158 
     
    8784                        name = objMacro.getGeneric(0).getString(0); 
    8885                } 
    89                  
    90                  
     86 
    9187                if(!oldDefinitionsMacros.containsKey(name)) { 
    9288                        oldDefinitionsMacros.put(name, new ArrayList<Node>()); 
     
    115111                String name = funcMacro.getString(0); 
    116112                Node value  = funcMacro; 
    117                  
     113                         
    118114                if(!oldDefinitionsMacros.containsKey(name)) { 
    119115                        oldDefinitionsMacros.put(name, new ArrayList<Node>()); 
     
    457453 
    458454        public Object getFunctionMacro(String macroName) { 
    459                 return functionMacros.get(macroName); 
     455                if(isFunctionMacro(macroName)) { 
     456                        if (lastBranchMacrosFunction != null) { 
     457                                if (lastBranchMacrosFunction.containsKey(macroName)) { 
     458                                        return lastBranchMacrosFunction.get(macroName); 
     459                                } 
     460                        } 
     461                         
     462                        return functionMacros.get(macroName); 
     463                } 
     464                return null; //TODO throws an exception  
     465                 
    460466        } 
    461467 
     
    468474        public Node retrieveMacro(String macroName) { 
    469475                Node macroNode = null; 
    470                 if( lastBranchMacrosFunction != null ) { 
    471                         if(lastBranchMacrosFunction.containsKey(macroName)) { 
    472                                 macroNode = getMacro(lastBranchMacrosFunction, macroName); 
    473                         } 
    474                 } else if(functionMacros.containsKey(macroName)) { 
    475                         macroNode = getMacro(functionMacros, macroName); 
    476                 } 
    477  
    478                 if( lastBranchMacrosObject != null ) { 
    479                         if( lastBranchMacrosObject.containsKey(macroName)) { 
    480                                 macroNode = getMacro(lastBranchMacrosObject, macroName); 
    481                         } 
    482                 } else if(objectMacros.containsKey(macroName)) { 
    483                         macroNode = getMacro(objectMacros, macroName); 
    484                 } 
    485  
     476        if(isFunctionMacro(macroName)) { 
     477            if( lastBranchMacrosFunction != null ) { 
     478                if(lastBranchMacrosFunction.containsKey(macroName)) { 
     479                    macroNode = getMacro(lastBranchMacrosFunction, macroName); 
     480                } 
     481            } 
     482             
     483            if(functionMacros.containsKey(macroName)) { 
     484                macroNode = getMacro(functionMacros, macroName); 
     485            } 
     486             
     487        } else if(isObjectMacro(macroName)) { 
     488            if( lastBranchMacrosObject != null ) { 
     489                if( lastBranchMacrosObject.containsKey(macroName)) { 
     490                    macroNode = getMacro(lastBranchMacrosObject, macroName); 
     491                } 
     492            } 
     493 
     494            if(objectMacros.containsKey(macroName)) { 
     495                macroNode = getMacro(objectMacros, macroName); 
     496            } 
     497        } 
    486498                return macroNode; 
    487499        } 
     
    521533        } 
    522534         
    523          
     535        /* 
    524536        public void updateDefine(String macroName) { 
    525537                if(!currentDefinitionIndex.containsKey(macroName)){ 
     
    528540                        currentDefinitionIndex.put(macroName, currentDefinitionIndex.get(macroName) + 1); 
    529541                } 
    530                  
     542                         
    531543                currentDefinitionMacros.put(macroName, oldDefinitionsMacros.get(macroName).get(0)); 
    532544        } 
     
    535547                //The macro that we undef is not defined 
    536548                currentDefinitionMacros.put(macroName, null); 
    537  
    538         } 
     549        }  
     550         
     551        public Node retrieveMacroAnalysis(String macroName) { 
     552        return currentDefinitionMacros.get(macroName); 
     553        }*/ 
    539554         
    540555         
  • trunk/cpp_analysis/src/xtc/lang/c4/C4ParseTreePrinter.java

    r185 r196  
    3535  } 
    3636   
     37  public void visitMacroBased4(GNode n) { 
     38          int i = 0; 
     39          for (Object o : n) { 
     40                  //We do not want to consider the last child since this is the definition 
     41                  if ((o instanceof Node) && (i < n.size() - 1)) 
     42                          dispatch((Node)o); 
     43                  i++; 
     44          } 
     45  } 
     46   
    3747  public void visitUserHeader(GNode n) { 
    3848           
    3949           for (Object o : n) { 
    4050                     if (o instanceof Node) { 
    41                          if(((Node)o).getName() == "Include") 
     51                         if(((Node)o).getName().equals("Include")) 
    4252                         dispatch((Node)o); 
    4353                     } 
     
    4959           for (Object o : n) { 
    5060                     if (o instanceof Node) { 
    51                          if(((Node)o).getName() == "Include") 
     61                         if(((Node)o).getName().equals("Include")) 
    5262                         dispatch((Node)o); 
    5363                     } 
  • trunk/cpp_analysis/src/xtc/lang/c4/C4ParserState.java

    r192 r196  
    553553 
    554554 
    555           if(n.getString(1) == "<<")  
     555          if(n.getString(1).equals("<<"))  
    556556            result = tmp1 << tmp2; 
    557557 
     
    597597          tmp2  = string2long(tmpS2); 
    598598 
    599           if(n.get(1) == "<")  
     599          if(n.get(1).equals("<"))  
    600600            result = tmp1 < tmp2 ?  1 : 0; 
    601           else if (n.get(1) == ">") 
     601          else if (n.get(1).equals(">")) 
    602602            result = tmp1 > tmp2 ?  1 : 0; 
    603             else if (n.get(1) == ">=") 
     603            else if (n.get(1).equals(">=")) 
    604604              result = tmp1 >= tmp2 ? 1 : 0; 
    605               else if (n.get(1) == ">=") 
     605              else if (n.get(1).equals(">=")) 
    606606                result = tmp1 >= tmp2 ? 1 : 0; 
    607607 
     
    617617          tmpS2 = dispatch((Node)n.get(2)).toString(); 
    618618          tmp2  = string2long(tmpS2); 
    619           if(n.get(1) == "==")  
     619          if(n.get(1).equals("=="))  
    620620            result = tmp1 == tmp2 ?  1 : 0; 
    621           else if (n.get(1) == "!=") 
     621          else if (n.get(1).equals("!=")) 
    622622            result = tmp1 != tmp2 ?  1 : 0; 
    623623 
     
    635635          tmp2  = string2long(tmpS2); 
    636636 
    637           if(n.get(1) == "+")  
     637          if(n.get(1).equals("+"))  
    638638            result = tmp1+tmp2; 
    639           else if (n.get(1) == "-") 
     639          else if (n.get(1).equals("-")) 
    640640            result = tmp1-tmp2; 
    641641 
     
    653653 
    654654 
    655           if(n.get(1) == "*")  
     655          if(n.get(1).equals("*"))  
    656656            result = tmp1*tmp2; 
    657           else if (n.get(1) == "/") 
     657          else if (n.get(1).equals("/")) 
    658658            result = tmp1/tmp2; 
    659           else if (n.get(1) == "%") 
     659          else if (n.get(1).equals("%")) 
    660660            result = tmp1%tmp2; 
    661661          return Long.toString(result); 
     
    818818 
    819819 
    820             if(n.getString(1) == "<<")  
     820            if(n.getString(1).equals("<<"))  
    821821              result = tmp1 << tmp2; 
    822822 
     
    865865            tmp2  = string2long(tmpS2); 
    866866 
    867             if(n.getString(1) == "<")  
     867            if(n.getString(1).equals("<"))  
    868868              result = tmp1 < tmp2 ?  1 : 0; 
    869             else if (n.getString(1) == ">") 
     869            else if (n.getString(1).equals(">")) 
    870870              result = tmp1 > tmp2 ?  1 : 0; 
    871               else if (n.getString(1) == ">=") 
     871              else if (n.getString(1).equals(">=")) 
    872872                result = tmp1 >= tmp2 ? 1 : 0; 
    873                 else if (n.getString(1) == ">=") 
     873                else if (n.getString(1).equals(">=")) 
    874874                  result = tmp1 >= tmp2 ? 1 : 0; 
    875875 
     
    885885            tmpS2 = dispatch((Node)n.get(2)).toString(); 
    886886            tmp2  = string2long(tmpS2); 
    887             if(n.getString(1) == "==")  
     887            if(n.getString(1).equals("=="))  
    888888              result = tmp1 == tmp2 ?  1 : 0; 
    889             else if (n.getString(1) == "!=") 
     889            else if (n.getString(1).equals("!=")) 
    890890              result = tmp1 != tmp2 ?  1 : 0; 
    891891 
     
    904904 
    905905 
    906             if(n.getString(1) == "+")  
     906            if(n.getString(1).equals("+"))  
    907907              result = tmp1+tmp2; 
    908             else if (n.getString(1) == "-") 
     908            else if (n.getString(1).equals("-")) 
    909909              result = tmp1-tmp2; 
    910910 
     
    922922 
    923923 
    924             if(n.getString(1) == "*")  
     924            if(n.getString(1).equals("*"))  
    925925              result = tmp1*tmp2; 
    926             else if (n.getString(1) == "/") 
     926            else if (n.getString(1).equals("/")) 
    927927              result = tmp1/tmp2; 
    928             else if (n.getString(1) == "%") 
     928            else if (n.getString(1).equals("%")) 
    929929              result = tmp1%tmp2; 
    930930 
     
    969969      else  
    970970      { 
    971         throw new MacroUndefException(macroName); 
     971       throw new MacroUndefException(macroName); 
    972972      } 
    973973      return macroValue; 
     
    17251725      } 
    17261726      
    1727       if(op == ">") 
     1727      if(op.equals(">")) 
    17281728        result = ( leftValueI > rightValueI); 
    1729       if(op == ">=") 
     1729      if(op.equals(">=")) 
    17301730        result = ( leftValueI >= rightValueI); 
    1731       if(op == "<") 
     1731      if(op.equals("<")) 
    17321732        result = ( leftValueI < rightValueI); 
    1733       if(op == "<="){ 
     1733      if(op.equals("<=")) { 
    17341734       result = ( leftValueI <= rightValueI); 
    17351735      } 
     
    17771777      Node tmpArithmeticExpression = arithmeticExpression.strip(); 
    17781778      Long tmpCompute; 
    1779       if (tmpArithmeticExpression.getName() == "IfGroupAdditiveExpression" ||  
    1780           tmpArithmeticExpression.getName() == "IfGroupMultiplicativeExpression" ||  
    1781           tmpArithmeticExpression.getName() == "IfGroupBinaryExpression" || 
    1782           tmpArithmeticExpression.getName() == "FunctionMacroCallExpression") { 
     1779      if (tmpArithmeticExpression.getName().equals("IfGroupAdditiveExpression") ||  
     1780          tmpArithmeticExpression.getName().equals("IfGroupMultiplicativeExpression") ||  
     1781          tmpArithmeticExpression.getName().equals("IfGroupBinaryExpression") || 
     1782          tmpArithmeticExpression.getName().equals("FunctionMacroCallExpression")) { 
    17831783 
    17841784        tmpCompute = computeVisitor(tmpArithmeticExpression); 
     
    17871787 
    17881788      } else { 
    1789         if (tmpArithmeticExpression.getName() == "IntegerConstant" ) { 
     1789        if (tmpArithmeticExpression.getName().equals("IntegerConstant") ) { 
    17901790          try { 
    17911791            String tmpS = tmpArithmeticExpression.getString(0); 
     
    18031803        } 
    18041804      } else { 
    1805         if ( tmpArithmeticExpression.getName() == "DefinedExpressionID") {  
     1805        if ( tmpArithmeticExpression.getName().equals("DefinedExpressionID")) {  
    18061806            //in the case the macro is not defined but still used... 
    18071807            //its value is 0 
     
    18281828        tmp1 = (Long) dispatch((Node)n.get(0)); 
    18291829        tmp2 = (Long) dispatch((Node)n.get(2)); 
    1830         if(n.getString(1) == "+")  
     1830        if(n.getString(1).equals("+"))  
    18311831          result = tmp1+tmp2; 
    1832         else if (n.getString(1) == "-") 
     1832        else if (n.getString(1).equals("-")) 
    18331833          result = tmp1-tmp2; 
    18341834 
     
    18421842        tmp1 = ((Long) dispatch((Node)n.get(0))).longValue(); 
    18431843        tmp2 = ((Long) dispatch((Node)n.get(2))).longValue(); 
    1844         if( tmp2 == 0 && ((n.getString(1)== "%") || (n.getString(1) =="/"))) { 
     1844        if( tmp2 == 0 && ((n.getString(1).equals("%")) || (n.getString(1).equals("/")))) { 
    18451845          tmp2 =1; 
    18461846        } 
    1847         if(n.getString(1) == "*")  
     1847        if(n.getString(1).equals("*")) 
    18481848          result = tmp1*tmp2; 
    1849         else if (n.getString(1) == "/") 
     1849        else if (n.getString(1).equals("/")) 
    18501850          result = tmp1/tmp2; 
    1851         else if (n.getString(1) == "%") 
     1851        else if (n.getString(1).equals("%")) 
    18521852          result = tmp1%tmp2; 
    18531853 
     
    18611861        tmp1 = ((Long) dispatch((Node)n.get(0))).longValue(); 
    18621862        tmp2 = ((Long) dispatch((Node)n.get(2))).longValue(); 
    1863         if(n.getString(1) == "&")  
     1863        if(n.getString(1).equals("&")) 
    18641864          result = tmp1&tmp2; 
    1865         else if (n.getString(1) == "|") 
     1865        else if (n.getString(1).equals("|")) 
    18661866          result = tmp1|tmp2; 
    18671867 
     
    18831883        tmp1 = ((Long) dispatch((Node)n.get(0))).longValue(); 
    18841884        tmp2 = ((Long) dispatch((Node)n.get(2))).longValue(); 
    1885         if(n.getString(1) == "<<") 
     1885        if(n.getString(1).equals("<<")) 
    18861886          result = tmp1 << tmp2; 
    18871887 
     
    19661966 
    19671967 
    1968         if(n.getString(1) == "<<")  
     1968        if(n.getString(1).equals("<<"))  
    19691969          result = tmp1 << tmp2; 
    19701970 
     
    20102010        tmp2  = string2long(tmpS2); 
    20112011 
    2012         if(n.getString(1) == "<")  
     2012        if(n.getString(1).equals("<"))  
    20132013          result = tmp1 < tmp2 ?  1 : 0; 
    2014         else if (n.getString(1) == ">") 
     2014        else if (n.getString(1).equals(">")) 
    20152015          result = tmp1 > tmp2 ?  1 : 0; 
    2016           else if (n.getString(1) == ">=") 
     2016          else if (n.getString(1).equals(">=")) 
    20172017            result = tmp1 >= tmp2 ? 1 : 0; 
    2018             else if (n.getString(1) == ">=") 
     2018            else if (n.getString(1).equals(">=")) 
    20192019              result = tmp1 >= tmp2 ? 1 : 0; 
    20202020 
     
    20302030        tmpS2 = dispatch((Node)n.get(2)).toString(); 
    20312031        tmp2  = string2long(tmpS2); 
    2032         if(n.getString(1) == "==")  
     2032        if(n.getString(1).equals("=="))  
    20332033          result = tmp1 == tmp2 ?  1 : 0; 
    2034         else if (n.getString(1) == "!=") 
     2034        else if (n.getString(1).equals("!=")) 
    20352035          result = tmp1 != tmp2 ?  1 : 0; 
    20362036 
     
    20472047        tmpS2 = dispatch((Node)n.get(2)).toString(); 
    20482048        tmp2  = string2long(tmpS2); 
    2049         if(n.getString(1) == "+")  
     2049        if(n.getString(1).equals("+"))  
    20502050          result = tmp1+tmp2; 
    2051         else if (n.getString(1) == "-") 
     2051        else if (n.getString(1).equals("-")) 
    20522052          result = tmp1-tmp2; 
    20532053 
     
    20652065 
    20662066 
    2067         if(n.getString(1) == "*")  
     2067        if(n.getString(1).equals("*"))  
    20682068          result = tmp1*tmp2; 
    2069         else if (n.getString(1) == "/") 
     2069        else if (n.getString(1).equals("/")) 
    20702070          result = tmp1/tmp2; 
    2071         else if (n.getString(1) == "%") 
     2071        else if (n.getString(1).equals("%")) 
    20722072          result = tmp1%tmp2; 
    20732073        return Long.valueOf(result); 
     
    22462246  public boolean isBlockBeginning(String macroIsBegin) { 
    22472247    boolean result = false; 
     2248     
    22482249    if(!isMacro(macroIsBegin)) 
    22492250      result = false; 
    22502251    else { 
    2251       result = visitForCurly("{", getMacro(macroIsBegin)); 
     2252      Node macroNode = getMacro(macroIsBegin); 
     2253       
     2254      if(macroNode == null) { 
     2255        result = false; 
     2256      } else { 
     2257        result = visitForCurly("{", macroNode); 
     2258      } 
    22522259    } 
    22532260    return result; 
     
    22642271      result = false; 
    22652272    else { 
     2273      Node macroNode = getMacro(macroIsEnd); 
     2274      if(macroNode == null){  
     2275        result = false; 
     2276      } else { 
    22662277      result = visitForCurly("}", getMacro(macroIsEnd)); 
     2278      } 
    22672279    } 
    22682280    return result; 
  • trunk/cpp_analysis/src/xtc/lang/c4/CPPAnalyzer.java

    r193 r196  
    11851185                        for (int i = 0; i < size; i++) {         
    11861186                                final GNode declaration = declarationList.getGeneric(i); 
    1187  
    11881187                                if(declaration.size() < 2) { 
    11891188 
     
    11941193 
    11951194                                        if(null != name) { 
    1196                                                 if(declaration.getGeneric(0).getName() == "IfSection") { 
     1195                        String declarationName = declaration.getGeneric(0).getName(); 
     1196                                                if(declarationName.equals("IfSection")) { 
    11971197                                                        c4log.logStructCond(name, i== size - 1 , declaration.getLocation()); 
    1198                                                 } 
     1198                                                } else if(declarationName.equals("Define")) { 
     1199                            dispatch(declaration.getGeneric(0));  
     1200                        } 
    11991201                                        }      
    12001202                                } else { 
     
    12611263                        } 
    12621264                } 
     1265 
     1266        /** Visit the specified macro Definition. 
     1267         *  Just to check if the macro is conditionally defined  
     1268         *  Duplicate of the global visitor because of the specifiers subclass 
     1269         **/  
     1270         
     1271        public void visitDefine(GNode define) { 
     1272            String name="";  
     1273            String kind = define.getGeneric(0).getName(); 
     1274            if(kind.equals("FunctionMacro")) { 
     1275                name = define.getGeneric(0).getString(0); 
     1276            } else if(kind.equals("ObjectMacro")) { 
     1277                name = define.getGeneric(0).getGeneric(0).getString(0);                  
     1278            } else if(kind.equals("Undef")) { 
     1279                        name = define.getGeneric(0).getGeneric(0).getString(0); 
     1280                        conditionalDefs.remove(name); 
     1281                return; 
     1282            } 
     1283 
     1284            if(isConditionallyDefined(define) && configOptions.size() > 0) {  
     1285                if(0 != conditionStack.size() && !name.equals("")) { 
     1286                    if(markedConfigOptions.size() > 0) // We add this function only if the condition is based on a config option 
     1287                        conditionalDefs.put(name, markedConfigOptions ); 
     1288                } else { 
     1289                    try{ 
     1290                        throw new NullPointerException(); 
     1291                    }catch(NullPointerException npe) { 
     1292                        System.err.println("Problem with the conditional definitions visitDefine " + define.getLocation() 
     1293                                ); 
     1294                        npe.printStackTrace(); 
     1295                        conditionalDefs.put(name, null); 
     1296                    } 
     1297                } 
     1298 
     1299            } 
     1300        } 
    12631301 
    12641302                /** Process the complex type specifier. */ 
     
    22962334        public static String getDeclaredIdName(GNode declarator) { 
    22972335                String functionName = "Fuction Name"; 
    2298                 if (declarator.getName() == "IfSection") { 
     2336                if (declarator.getName().equals("IfSection")) { 
    22992337                        functionName = (String) new Visitor() { 
    23002338                                String name; 
     
    25972635 
    25982636                StringWriter tmpString = c4log.init_logging(dbStore); 
    2599  
    26002637                if(cmdLineHeaders != null) { 
    26012638                        //if header files were given on the command line, we dispatch them... 
     
    26102647                //Dispatching the top level 
    26112648                dispatch(unit); 
    2612  
    26132649                //Extraction 
    26142650                if(null != extract && atTopLevelFile()) { 
     
    26182654 
    26192655                c4log.dumpResults(tmpString, ifSectionNumber, macroNumber); 
    2620  
    26212656                return table; 
    26222657        } 
     
    34503485                                                        + elsen.get(0)); 
    34513486                                } 
     3487                                 
    34523488                                if (elsen.getGeneric(0).getName() != "Unparsed") { 
    34533489                                        //This condition holds. 
     
    35143550                                } 
    35153551 
    3516                                 if (ifDefn.getGeneric(1).getName() != "Unparsed") {//unnecessary test, if it's a config option, this is parsed 
    3517                                         if(configOptions.contains(ifDefn.getString(0))) //If this is a config option 
     3552                                if (ifDefn.getGeneric(1).getName() != "Unparsed") { 
     3553                                        if(configOptions.contains(ifDefn.getString(0))) { //If this is a config option 
    35183554                                                tmpConfigOptions.add(ifDefn.getString(0)); 
    3519                                 }            
     3555                                        }  
     3556                                } else { //We log the config options which are not defined anyway 
     3557                                        if (ifDefn.getString(0).startsWith("CONFIG_")) { 
     3558                                                tmpNDefConfigOptions.add("!" + ifDefn.getString(0)); 
     3559                                        } 
     3560                                }           
    35203561                        } 
    35213562 
     
    35273568 
    35283569                                //ConfigOptions which are not defined should not hold, so we only log them to build for the else 
    3529                                 if(configOptions.contains(ifNDefn.getString(0))) //If this is a config option 
    3530                                         tmpNDefConfigOptions.add(ifNDefn.getString(0)); 
     3570                                if (ifNDefn.getGeneric(1).getName() != "Unparsed") { 
     3571                                        //the ifndef condition is true 
     3572                                        //we check if the condition is a potential config option 
     3573                                        if (ifNDefn.getString(0).startsWith("CONFIG_")) { 
     3574                                                //Config Option, we log it 
     3575                                                tmpConfigOptions.add("!" + ifNDefn.getString(0)); 
     3576                                        } 
     3577                                } else { 
     3578                                        if(configOptions.contains(ifNDefn.getString(0))) { //If this is a config option 
     3579                                                tmpNDefConfigOptions.add(ifNDefn.getString(0)); 
     3580                                        } 
     3581                                } 
    35313582                        } 
    35323583 
     
    37293780 
    37303781 
    3731                         } else if (functionBody.getGeneric(index+1).getName() == "ReturnStatement") { //just before a return 
     3782                        } else if (functionBody.getGeneric(index+1).getName().equals("ReturnStatement")) { //just before a return 
    37323783                                result = true; 
    37333784                        } 
     
    54685519                                        if (macroDefinition.getGeneric(1).get(0) instanceof Node) { 
    54695520                                                if (macroDefinition.getGeneric(1).getNode(0).strip() != null) { 
    5470                                                         //System.out.println("NULL AFTER STRIP " + macroDefinition.getGeneric(1).getNode(0)); 
    5471                                                         //System.out.println("MACRODEF GET GEN 1" + macroDefinition.getGeneric(1)); 
    5472                                                         //System.out.println("MACRODEF GET GEN 1STRIPPED " + macroDefinition.getGeneric(1).strip()); 
    5473                                                         //System.out.println("MACRO GETGENERIC " + macroDefinition.getGeneric(1).size()); 
    5474                                                         //     System.exit(-1); 
    5475  
    5476                                                         // else  
    54775521                                                        if (macroDefinition.getGeneric(1).getNode(0).strip().isGeneric()) { 
    54785522                                                                if (macroDefinition.getGeneric(1).getGeneric(0) != null) { 
     
    57265770                        public void visitCPPIdentifierList(GNode n) { 
    57275771                                for(int i=0; i < n.size(); i++) { 
    5728                                         //System.out.println("ADDING " + n.getString(i)); 
    57295772                                        idsInMacro.add(n.getString(i)); 
    57305773                                } 
     
    70197062        /** Visit the specified macro Definition. 
    70207063         *  Just to check if the macro is conditionally defined */ 
    7021  
    70227064        public void visitDefine(GNode define) { 
    7023                 String name="";  
     7065        String name="";  
    70247066                String kind = define.getGeneric(0).getName(); 
    70257067                if(kind.equals("FunctionMacro")) { 
    70267068                        name = define.getGeneric(0).getString(0); 
    7027                         macrosManager.updateDefine(name); 
    70287069                } else if(kind.equals("ObjectMacro")) { 
    70297070                        name = define.getGeneric(0).getGeneric(0).getString(0);                  
    7030                         macrosManager.updateDefine(name); 
    70317071                } else if(kind.equals("Undef")) { 
     7072                        name = define.getGeneric(0).getGeneric(0).getString(0); 
     7073                        conditionalDefs.remove(name); 
    70327074                        return; 
    70337075                } 
     
    79477989                        } 
    79487990 
     7991                        //Logging  
     7992                        //if(!alreadyConsideredFunctionCall() &&) { 
    79497993                        // CONVERTIBLE BEFORE  
    79507994                        convertibleBefore = isConvertibleBefore(n); 
     
    79678011                        funcDefLoc = ((GNode)functionDefinitions.get(name)).getLocation(); 
    79688012                        if (conditionalDefs.containsKey(name)) { 
     8013                                 
     8014                                 
    79698015                                c4log.logWrapper("Function", name, funcDefLoc, loc, conditionStack, markedConfigOptionsStack, condDefs, movableBefore, movableAfter, convertibleBefore, convertibleAfter); 
    79708016                                clogger.setConvertibleBeforeFuncCall(conditionalDefs.get(name), loc,convertibleBefore); 
     
    79738019 
    79748020                        } 
    7975                         //                      c4log.logBeforeInfo("Function", name, funcDefLoc, loc, movableBefore, conditionStack, condDefs); 
    7976                         //                      c4log.logAfterInfo("Function", name, funcDefLoc, movableAfter, n 
    7977                         //                                      .getLocation(), conditionStack, condDefs); 
    7978  
     8021                        //}// END OF LOGGING 
    79798022                        //END OF ANALYSIS REPORT  
    79808023                } 
     
    82578300                        if(null != extract && atTopLevelFile()) { 
    82588301                                if(markedConfigOptions.contains(extract)) { 
    8259                                         toExtract.add(new C4Extractable(functionDefinitionName, funcDef,n, "before")); 
     8302                                        if(isInFunctionBody() && funcDef != null) { //To Be sure we are inside a function 
     8303                                                toExtract.add(new C4Extractable(functionDefinitionName, funcDef,n, "before")); 
     8304                                        } else { 
     8305                                                //toExtract.add(new C4Extractable(null, null, n, "before")); 
     8306                                                //System.out.println("NODE " + n); 
     8307                                        } 
    82608308                                } 
    82618309                        } 
     
    83668414         *@return The node associated with the macroName 
    83678415         * */ 
    8368         public Node retrieveMacroAnalysis(String macroName) { 
    8369                 Node macro = macrosManager.retrieveMacro(macroName); 
    8370  
    8371                 if(macro != null) 
    8372                         return macro; 
    8373  
    8374                 if(macrosManager.getRemovedMacros().containsKey(macroName)) 
    8375                 { 
    8376                         return (Node) macrosManager.getRemovedMacros().get(macroName).get(macrosManager.getRemovedMacros().get(macroName).size() - 1); 
    8377                 } 
    8378  
    8379                 return null; 
    8380  
    8381         } 
     8416        /*public Node retrieveMacroAnalysis(String macroName) { 
     8417                return macrosManager.retrieveMacroAnalysis(macroName); 
     8418        }*/ 
    83828419 
    83838420        /** Visit the specified if else statement. */ 
     
    86118648                Node parameters = n.getGeneric(parameterPosition) != null ? n.getGeneric(parameterPosition) : null; // FunctionMacroCallParametersList 
    86128649                String macroName =  n.getString(macroNamePosition); 
    8613                 Node macroDefinition = retrieveMacroAnalysis(macroName); 
    8614                 Location macroDefLoc = macroDefinition.getLocation(); 
    8615                 if (1 <= DEBUG) { 
     8650                 
     8651                 
     8652                //Node macroDefinition = retrieveMacroAnalysis(macroName); 
     8653                 
     8654                Node macroDefinition = n.getNode(n.size()-1); 
     8655                 
     8656        Location macroDefLoc = macroDefinition.getLocation(); 
     8657 
     8658        if (1 <= DEBUG) { 
    86168659                        if(macroDefinition == null) { 
    86178660                                System.out.println("MACRO " + macroName + " LOCATION " + n.getLocation()); 
     
    86878730                } 
    86888731                // 
    8689  
    86908732                //Extraction 
    86918733                if(null != extract) { 
     
    86998741                } 
    87008742 
     8743                 
     8744                 
     8745                // 
     8746                 
    87018747                //BEFORE 
    87028748                 
    87038749                //We've already seen a return statement we cannot move this macro 
    87048750                //Or this is in the right hand side of an assignement 
     8751                 
     8752                 
     8753                 
    87058754                if((returnSeen || rightHandSide) || (ifsNode.size() > 0) || (loopsNode.size() > 0) || !inFuncBody) { 
    87068755                        //if((returnSeen) || (rightHandSide)){ 
     
    87218770                ArrayList<String> defs = conditionalDefs.get(macroName); 
    87228771                movableAfter = isMovableAfterFunctionMacroRef(n, idsInMacro, inFuncBody); 
    8723  
     8772                 
     8773                //SIGNATURE  
     8774                if(!atTopLevelFile()) {// We look at the signatures for header files 
     8775                        if(logger.alreadyConsideredMacro(n.getGeneric(n.size()-1), macroName, loc.toString())) { 
     8776                                return ; 
     8777                        } 
     8778                } 
     8779 
     8780                 
    87248781                c4log.logWrapper("MacroReference", macroName, macroDefLoc, loc, conditionStack, markedConfigOptionsStack, defs, movableBefore, movableAfter, convertibleBefore, convertibleAfter); 
    87258782 
     
    87468803        public void visitMacroReference(GNode n) { 
    87478804                String macroName = n.getString(0); 
    8748                 Node macroDefinition = retrieveMacroAnalysis(macroName); 
     8805                //Node macroDefinition = retrieveMacroAnalysis(macroName); 
     8806        Node macroDefinition = n.getNode(n.size()- 1); 
    87498807                Location macroDefLoc = macroDefinition.getLocation(); 
     8808                 
    87508809                // We need to know what is the scope hierarchy 
    87518810                // We only want to analyze when the macro is in a function 
     
    91519210                        scope = scope.getParent(); 
    91529211                        if (scope != null) { 
    9153                                 if (scope.getName() == "") // Macro 
     9212                                if (scope.getName().equals("")) // Macro 
    91549213                                        return ErrorT.TYPE; 
    91559214                        } else { 
     
    94729531                } 
    94739532 
    9474                 if( reanalyze || !logger.alreadyConsidered(headerName, header.getGeneric(1))) 
     9533                if( reanalyze || !logger.alreadyConsideredTree(headerName, header.getGeneric(1))) 
    94759534                        dispatch(header.getGeneric(1)); 
    94769535 
     
    94869545                } 
    94879546 
    9488                 if( reanalyze || !logger.alreadyConsidered(headerName, header.getGeneric(1))) 
     9547                if( reanalyze || !logger.alreadyConsideredTree(headerName, header.getGeneric(1))) 
    94899548                        dispatch(header.getGeneric(1)); 
    94909549 
  • trunk/cpp_analysis/src/xtc/lang/c4/DBHandler.java

    r172 r196  
    5959        /** A Prepared to select nodes with the same hash signature **/ 
    6060        PreparedStatement query; 
     61        /** A PreparedStatement to insert new trees in the database  **/ 
     62        PreparedStatement newMacro; 
     63        /** A Prepared to find whether the macrodefinition associated with a particular location remains the same 
     64         *  with the same hash signature **/ 
     65        PreparedStatement queryMacro; 
     66        /** A PreparedStatement to insert new funcCall in the database  **/ 
     67        PreparedStatement newFuncCall; 
     68        /** A Prepared to find whether the function definition associated with a particular location remains the same 
     69         *  with the same hash signature **/ 
     70        PreparedStatement queryFuncCall; 
    6171        /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 
    6272        PreparedStatement convUpdateBeforeSection; 
     
    119129                        query = conn.prepareStatement("select node from treesMD5 where hash==? ;"); 
    120130 
     131                        //Table to avoid recounting the same macro twice when analyzing 
     132                        //Keeps track of the macroDefinition signature associated with one refLocation 
     133                        stmt.executeUpdate("create table if not exists macrosMD5 (id INTEGER PRIMARY KEY ASC, " + 
     134                                        "hashDef BINARY[16], macroName TEXT, refLocation TEXT); "); 
     135                        newMacro = conn.prepareStatement( 
     136                        "insert into macrosMD5(hashDef, macroName, refLocation) values(?, ?, ?);"); 
     137                        queryMacro = conn.prepareStatement("select macroName from macrosMD5 where (hashDef==? AND refLocation==?) ;"); 
     138                         
     139                        //Table to avoid recounting the same funcCall twice when analyzing 
     140                        //Keeps track of the macroDefinition signature associated with one refLocation 
     141                        stmt.executeUpdate("create table if not exists funcCallMD5 (id INTEGER PRIMARY KEY ASC, " + 
     142                                        "hashDef BINARY[16], funcName TEXT, callLocation TEXT); "); 
     143                        newFuncCall = conn.prepareStatement( 
     144                        "insert into funcCallMD5 (hashDef, funcName, callLocation) values(?, ?, ?);"); 
     145                        queryFuncCall= conn.prepareStatement("select funcName from funcCallMD5 where (hashDef==? AND callLocation==?) ;"); 
     146                         
     147                         
    121148                        //Table to collect convertible information per location with CONFIG_OPTION 
    122149                        stmt.executeUpdate("create table if not exists convertibleLocation (id INTEGER PRIMARY KEY ASC, configOption TEXT, kind TEXT " + 
     
    249276                        //release_db(dbLock); 
    250277                         
    251             query.setBytes(1, hash); 
     278           //squery.setBytes(1, hash); 
    252279            conn.commit(); 
    253280                } catch (SQLException e) { 
     
    293320        } 
    294321 
     322        /** 
     323         * Adding a MacroReference with a new signature for a particular location 
     324         * @param headerRoot The node representing the root of the header file to add. 
     325         * @param hName The name of the header file to add. 
     326         * @param includingName The name of the file including this header file. 
     327         */ 
     328        public void addFuncCallTree(byte[] hash, String funcName, String callLocation) { 
     329                Pair<FileLock, RandomAccessFile> dbLock; 
     330                try { 
     331                        //newTree.clearBatch(); 
     332                        conn.setAutoCommit(false); 
     333            if(16 == hash.length ) { 
     334                                newFuncCall.setBytes(1, hash); 
     335                         
     336                        } 
     337                        else { 
     338                                System.err.println("Problem with the MD5 We're exiting..." ); 
     339                                System.exit(0); 
     340                        } 
     341             
     342                newFuncCall.setString(2, funcName); 
     343                        newFuncCall.setString(3, callLocation); 
     344                         
     345                        //System.out.println("NEW MACRO " + newMacro); 
     346                         
     347            //dbLock = lock_db(); 
     348                        newFuncCall.executeUpdate(); 
     349                        //release_db(dbLock); 
     350                         
     351            conn.commit(); 
     352                } catch (SQLException e) { 
     353                        System.err.println("Updating error: " + funcName + " at "+ callLocation + " not inserted in the table"); 
     354                        e.printStackTrace(); 
     355                } 
     356        } 
     357         
     358        /** 
     359         * Adding a MacroReference with a new signature for a particular location 
     360         * @param headerRoot The node representing the root of the header file to add. 
     361         * @param hName The name of the header file to add. 
     362         * @param includingName The name of the file including this header file. 
     363         */ 
     364        public void addMacroReferenceTree(byte[] hash, String macroName, String refLocation) { 
     365                Pair<FileLock, RandomAccessFile> dbLock; 
     366                try { 
     367                        //newTree.clearBatch(); 
     368                        conn.setAutoCommit(false); 
     369            if(16 == hash.length ) { 
     370                                newMacro.setBytes(1, hash); 
     371                         
     372                        } 
     373                        else { 
     374                                System.err.println("Problem with the MD5 We're exiting..." ); 
     375                                System.exit(0); 
     376                        } 
     377             
     378                newMacro.setString(2, macroName); 
     379                        newMacro.setString(3, refLocation); 
     380                         
     381                        //System.out.println("NEW MACRO " + newMacro); 
     382                         
     383            //dbLock = lock_db(); 
     384                        newMacro.executeUpdate(); 
     385                        //release_db(dbLock); 
     386                         
     387            conn.commit(); 
     388                } catch (SQLException e) { 
     389                        System.err.println("Updating error: " + macroName + " at "+ refLocation + " not inserted in the table"); 
     390                        e.printStackTrace(); 
     391                } 
     392        } 
     393 
     394        /**, 
     395         * Tells whether a particular macroReference refers to the same macroDefinition in the same context 
     396         * i.e. even if the global context is different the macro definition may not have changed 
     397         * @param the hash value to look for in the database 
     398         * @return An ArrayList representing all the GNodes associated with this hash value 
     399         */ 
     400        public boolean isThereMacroWithSameHash(byte[] hash, String refLocation) { 
     401                boolean result = false; 
     402                try { 
     403                        queryMacro.setBytes(1, hash); 
     404                        queryMacro.setString(2, refLocation); 
     405                         
     406                        ResultSet rs = queryMacro.executeQuery(); 
     407                         
     408                        while (rs.next()) { //We've found a macro with the same signature 
     409                                result = true; 
     410                                break; 
     411                        } 
     412                         
     413            rs.close(); 
     414                } catch (Exception e) { 
     415                        e.printStackTrace(); 
     416                } 
     417                 
     418                return result; 
     419        } 
     420         
     421        /**, 
     422         * Tells whether a particular function call refers to the same function Definition in the same context 
     423         * i.e. even if the global context is different the function definition may not have changed 
     424         * @param the hash value to look for in the database 
     425         * @return An ArrayList representing all the GNodes associated with this hash value 
     426         */ 
     427        public boolean isThereFuncCallWithSameHash(byte[] hash, String callLocation) { 
     428                boolean result = false; 
     429                try { 
     430                        queryFuncCall.setBytes(1, hash); 
     431                        queryFuncCall.setString(2, callLocation); 
     432                         
     433                        ResultSet rs = queryFuncCall.executeQuery(); 
     434                         
     435                        while (rs.next()) { //We've found a macro with the same signature 
     436                                result = true; 
     437                                break; 
     438                        } 
     439                         
     440            rs.close(); 
     441                } catch (Exception e) { 
     442                        e.printStackTrace(); 
     443                } 
     444                 
     445                return result; 
     446        } 
     447         
    295448        /**, 
    296449         * Returns all the GNodes associated with one particular MD5 digest in the database 
  • trunk/cpp_analysis/src/xtc/lang/c4/TreeLogger.java

    r103 r196  
    11package xtc.lang.c4; 
    22 
    3 import java.io.ByteArrayOutputStream; 
    4 import java.io.ObjectOutputStream; 
    5 import java.security.MessageDigest; 
    63import java.util.ArrayList; 
    74 
     
    1613         */ 
    1714        DBHandler dbHandler; 
     15         
     16        boolean DBGLogger = false; 
    1817 
    1918        public TreeLogger() { 
     
    2322 
    2423 
    25         private boolean compareByteArray(byte [] b1, byte[] b2 ) { 
    26                 if(b1.length != b2.length) 
    27                         return false; 
    28                 for(int i=0; i<b1.length; i++) { 
    29                         if(b1[i] !=  b2[i]) 
    30                                 return false; 
    31                 } 
    32                 return true;     
    33         } 
    34  
    35  
    36         private byte[] cryptoTest(GNode myNode) { 
    37                 // Create a Message Digest from a Factory method 
    38                 try { 
    39                         MessageDigest md = MessageDigest.getInstance("MD5"); 
    40                         ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    41                         ObjectOutputStream oos = new ObjectOutputStream(bos); 
    42                         oos.writeObject(myNode.toString()); 
    43                         oos.flush(); 
    44                         oos.close(); 
    45                         bos.close(); 
    46  
    47                         byte [] data = bos.toByteArray(); 
    48                         md.update(data); 
    49                          
    50                         byte [] dig = md.digest(); 
    51                          
    52                         return dig; 
    53                          
    54                 } catch (Exception e) { 
    55                         // TODO: handle exception 
    56                         e.printStackTrace(); 
    57                         return null; 
    58                 } 
    59  
    60         } 
     24         
    6125 
    6226        /** 
     
    8246                        return hash;     
    8347        } 
     48  
     49        /** 
     50         * Method to check whether a macro reference referring to the same definition has already been reported 
     51         * We look at the signature of the definition and the location. That should be unique key 
     52         * @param macroDef The definition associated with the reference 
     53         * @param macroName The name of the macro to consider 
     54         * @param refLocation The Location of the reference 
     55         * @return <code>true</code> if the file has already been considered 
     56         */ 
     57        public boolean alreadyConsideredMacro( GNode macroDef, String macroName, String refLocation) { 
     58                 
     59                //First we compute the new hash value 
     60                //int newHash = hashFunction(rootNode); 
     61                byte[] md5key = C4SignatureUtils.cryptoTest(macroDef); 
     62                 
     63                 
     64                //We look for the same hash value in the DB 
     65                if(dbHandler.isThereMacroWithSameHash(md5key, refLocation)) {  
     66                //We look for potential collisions by comparing the whole trees 
     67                //We've already considered that macro... 
     68                        //Right now we do not compare the trees. 
     69                    if (DBGLogger) { 
     70                        System.out.println("MACRO " + macroName + " LOCATION " + refLocation); 
     71                    } 
     72                        return true; 
     73            } else { 
     74                if (DBGLogger) { 
     75                System.out.println("ADDING " + macroName); 
     76                } 
     77                //At this point, we know that the tree has been already considered 
     78                //We insert it into the DB 
     79                dbHandler.addMacroReferenceTree(md5key, macroName, refLocation); 
     80                return false; 
     81        } 
     82                 
     83        } 
    8484 
     85         
     86         
     87        /** 
     88         * Method to check whether a function call referring to the same definition has already been reported 
     89         * We look at the signature of the definition and the location. That should be unique key 
     90         * @param macroDef The definition associated with the reference 
     91         * @param macroName The name of the macro to consider 
     92         * @param refLocation The Location of the reference 
     93         * @return <code>true</code> if the file has already been considered 
     94         */ 
     95        public boolean alreadyConsideredFuncCall( GNode funcDef, String funcName, String callLocation) { 
     96                //First we compute the new hash value 
     97                //int newHash = hashFunction(rootNode); 
     98                byte[] md5key = C4SignatureUtils.cryptoTest(funcDef); 
     99                 
     100                 
     101                //We look for the same hash value in the DB 
     102                if(dbHandler.isThereFuncCallWithSameHash(md5key, callLocation)) {  
     103                //We look for potential collisions by comparing the whole trees 
     104                //We've already considered that macro... 
     105                        //Right now we do not compare the trees. 
     106                    if (DBGLogger) { 
     107                        System.out.println("Func " + funcName + " LOCATION " + callLocation); 
     108                    } 
     109                        return true; 
     110            } else { 
     111         
     112                //At this point, we know that the tree has been already considered 
     113                //We insert it into the DB 
     114                dbHandler.addFuncCallTree(md5key, funcName, callLocation); 
     115                return false; 
     116        } 
     117                 
     118        }        
     119         
     120         
    85121        /** 
    86122         * Method to check whether a Node representing the root of an header file has already been considered. 
     
    89125         * @return <code>true</code> if the file has already been considered 
    90126         */ 
    91         public boolean alreadyConsidered(String name, GNode rootNode) { 
     127        public boolean alreadyConsideredTree(String name, GNode rootNode) { 
    92128                //First we compute the new hash value 
    93129                //int newHash = hashFunction(rootNode); 
    94                 byte[] md5key = cryptoTest(rootNode); 
     130                byte[] md5key = C4SignatureUtils.cryptoTest(rootNode); 
    95131                 
    96132                 
     
    98134                ArrayList<String> matchingTrees = dbHandler.getNodeWithSameHash(md5key); 
    99135                //We look for potential collisions by comparing the whole trees 
    100                 if(0 < matchingTrees.size()) { 
     136                 
     137        if(0 < matchingTrees.size()) { 
    101138                        //We've already considered that file... 
    102139                        //Right now we do not compare the trees. 
    103                         return true; 
     140                    //System.out.println("TREE " + name); 
     141            return true; 
    104142                } 
    105143 
    106                 //At this point, we know that the tree has been already considered 
     144                //At this point, we know that the tree has not been already considered 
    107145                //We insert it into the DB 
    108146                dbHandler.addHeaderTree(rootNode, name, md5key); 
     
    144182        } 
    145183         
     184         
     185         
     186         
    146187        /** 
    147188         * Gets the dbHandler associate with this treeLogger to be shared with the convertibleLogger