void visitorTraversal::visit(SgNode* n)
   {
  // On each node look for any comments of CPP directives
     SgLocatedNode* locatedNode = isSgLocatedNode(n);
     if (locatedNode != NULL)
        {
          AttachedPreprocessingInfoType* comments = locatedNode->getAttachedPreprocessingInfo();

          if (comments != NULL)
             {
               printf ("Found attached comments (to IR node at %p of type: %s): \n",locatedNode,locatedNode->class_name().c_str());
               int counter = 0;
               AttachedPreprocessingInfoType::iterator i;
               for (i = comments->begin(); i != comments->end(); i++)
                  {
                    printf ("          Attached Comment #%d in file %s (relativePosition=%s): classification %s :\n%s\n",
                         counter++,(*i)->get_file_info()->get_filenameString().c_str(),
                         ((*i)->getRelativePosition() == PreprocessingInfo::before) ? "before" : "after",
                         PreprocessingInfo::directiveTypeName((*i)->getTypeOfDirective()).c_str(),
                         (*i)->getString().c_str());
                  }
             }
            else
             {
               printf ("No attached comments (at %p of type: %s): \n",locatedNode,locatedNode->sage_class_name());
             }
        }
   }
示例#2
0
               void visit ( SgNode* n )
                  {
                    SgLocatedNode* locatedNode = isSgLocatedNode(n); 
                    if (locatedNode != NULL)
                       {
                         AttachedPreprocessingInfoType* comments = locatedNode->getAttachedPreprocessingInfo();

                         if (comments != NULL)
                            {
                              printf ("Found attached comments (at %p of type: %s): \n",locatedNode,locatedNode->sage_class_name());
                              AttachedPreprocessingInfoType::iterator i;
                              for (i = comments->begin(); i != comments->end(); i++)
                                 {
                                   ROSE_ASSERT ( (*i) != NULL );
                                   printf ("          Attached Comment (relativePosition=%s): %s\n",
                                        ((*i)->getRelativePosition() == PreprocessingInfo::before) ? "before" : "after",
                                        (*i)->getString().c_str());
#if 1
                                // This does not appear to be a valid object when read in from an AST file.
                                   printf ("Comment/Directive getNumberOfLines = %d getColumnNumberOfEndOfString = %d \n",(*i)->getNumberOfLines(),(*i)->getColumnNumberOfEndOfString());
#endif
#if 1
                                // This does not appear to be a valid object when read in from an AST file.
                                   (*i)->get_file_info()->display("comment/directive location");
#endif
                                 }
                            }
                       }
                  }
示例#3
0
  //Replace the unparsing of expanded macro calls with the actual macro call wherever possible
  void unparseMacroCalls(SgNode* searchTree)
  {
    //Traverse AST to find all macro calls and the nodes they are attached to
    findPreprocInfo findPre;
    findPre.traverse(searchTree, preorder);

    std::vector< std::pair<SgNode*, PreprocessingInfo*> >& wherePreprocIsAttached = findPre.wherePreprocIsAttached;

    //Replace expanded macro calls with actual macro call from pre-cpp wherever possible
    for( std::vector< std::pair<SgNode*, PreprocessingInfo*> >::iterator iItr = wherePreprocIsAttached.begin(); 
        iItr != wherePreprocIsAttached.end(); ++iItr)
    {
      SgStatement*       currentNode = isSgStatement( (*iItr).first );
      PreprocessingInfo* curPreproc  = (*iItr).second;

      ROSE_ASSERT(currentNode != NULL);

      std::vector<SgNode*> matchingSubTree;

      if ( matchMacroToSubtrees(currentNode->get_scope(), curPreproc, matchingSubTree) )
      {
        for(unsigned int i = 0; i < matchingSubTree.size(); i++)
        {
          SgLocatedNode* macroNode = isSgLocatedNode(matchingSubTree[i]);
          ROSE_ASSERT(macroNode != NULL);
          std::string replacementString = ( i ==0 ? curPreproc->getString() : "" );

          if( isSgExpression(macroNode) == NULL )
          {
#ifndef USE_ROSE
#ifndef ROSE_SKIP_COMPILATION_OF_WAVE
         // If we are using ROSE to compile ROSE source code then the Wave support is not present.
            PreprocessingInfo::rose_macro_call* macroCall = curPreproc->get_macro_call();

            if(macroCall->expanded_macro.size() > 0 && boost::wave::token_id(macroCall->expanded_macro.back()) != boost::wave::T_COLON)
              replacementString +=";";
#endif
#endif
          }

          std::cout << "Doing line replacement " << macroNode->unparseToString() << " with " << replacementString << std::endl;

#if 0
          std::string pos;
          curPreproc->display(pos);
          std::cout << macroNode->class_name() << " "<<  pos << std::endl;
#endif

          macroNode->addToAttachedPreprocessingInfo(new PreprocessingInfo(PreprocessingInfo::LineReplacement,
                replacementString,macroNode->get_file_info()->get_filenameString(),1,1,1,PreprocessingInfo::before));
        }

        
      };

       

    }
    
  };
示例#4
0
void
WalrusGraph::OutputEdges::visit ( SgNode* astNode )
   {
  // printf ("astNode = %p = %s \n",astNode,astNode->class_name().c_str());

     int numberOfNodes = node_to_index_map.size()+1;
     static int num = 0;

     SgLocatedNode* locatedNode = isSgLocatedNode(astNode);
     if ((isBinary == true) || (locatedNode != NULL && locatedNode->get_file_info()->isFrontendSpecific() == false))
        {
          if (isSgGlobal(astNode) == NULL)
             {
               printf ("            { @source=%d; @destination=%d; }",node_to_index_map[astNode->get_parent()],node_to_index_map[astNode]);
               *outputFilePtr << "            { @source=" << node_to_index_map[astNode->get_parent()] << "; @destination=" << node_to_index_map[astNode] << "; }";

               if (num < numberOfNodes-2)
                  {
                    printf (",");
                    *outputFilePtr << ",";
                  }
               printf ("\n");
               *outputFilePtr << endl;
             }
          
          num++;
        }
   }
示例#5
0
void
WalrusGraph::OutputNodes::visit ( SgNode* astNode )
   {
     int numberOfNodes = node_to_index_map.size();
     static int num = 0;

     SgLocatedNode* locatedNode = isSgLocatedNode(astNode);
     if ((isBinary == true) || (locatedNode != NULL && locatedNode->get_file_info()->isFrontendSpecific() == false))
        {
       // if (node_to_index_map[astNode] < numberOfNodes-2);
          if (num < numberOfNodes-1)
             {
               printf ("            { @id=%d; @value=T; }",node_to_index_map[astNode]);
               *outputFilePtr << "            { @id=" << node_to_index_map[astNode] << "; @value=T; }";
               if (num < numberOfNodes-2)
                  {
                    printf (",");
                    *outputFilePtr << ",";
                  }
               printf ("\n");
               *outputFilePtr << endl;
             }

          num++;
        }
   }
示例#6
0
void findPreprocInfo::visit(SgNode* n)
{

  // Add in the information from the current node
  SgLocatedNode* locatedNode = isSgLocatedNode(n);
  if (locatedNode != NULL)
  {
    AttachedPreprocessingInfoType* commentsAndDirectives = locatedNode->getAttachedPreprocessingInfo();

    if (commentsAndDirectives != NULL)
    {
      // printf ("Found attached comments (to IR node at %p of type: %s): \n",locatedNode,locatedNode->class_name().c_str());
      // int counter = 0;

      // Use a reverse iterator so that we preserve the order when using push_front to add each directive to the accumulatedList
      AttachedPreprocessingInfoType::reverse_iterator i;
      for (i = commentsAndDirectives->rbegin(); i != commentsAndDirectives->rend(); i++)
      {
        // The different classifications of comments and directives are in ROSE/src/frontend/SageIII/rose_attributes_list.h
        if ((*i)->getTypeOfDirective() == PreprocessingInfo::CMacroCall)
        {
          wherePreprocIsAttached.push_back(std::pair<SgNode*,PreprocessingInfo*>(n,*i) );
        }
      }
    }
  }


}
示例#7
0
// This function is not requied since the base class function is available and is preferred (for conformity).
std::string
CompassAnalyses::FunctionDefinitionPrototype::CheckerOutput::getString() const
{
     ROSE_ASSERT(getNodeArray().size() <= 1);

  // Default implementation for getString
     SgLocatedNode* locatedNode = isSgLocatedNode(getNode());
     std::string sourceCodeLocation;
     if (locatedNode != NULL)
        {
          Sg_File_Info* start = locatedNode->get_startOfConstruct();
          Sg_File_Info* end   = locatedNode->get_endOfConstruct();
          sourceCodeLocation = (end ? Compass::formatStandardSourcePosition(start, end) 
                                    : Compass::formatStandardSourcePosition(start));
       }
      else
       {
      // Else this could be a SgInitializedName or SgTemplateArgument (not yet moved to be a SgLocatedNode)
         Sg_File_Info* start = getNode()->get_file_info();
         ROSE_ASSERT(start != NULL);
         sourceCodeLocation = Compass::formatStandardSourcePosition(start);
       }

     std::string nodeName = getNode()->class_name();

  // The short description used here needs to be put into a separate function (can this be part of what is filled in by the script?)
  // return loc + ": " + nodeName + ": variable requiring static constructor initialization";

     return m_checkerName + ": " + sourceCodeLocation + ": " + nodeName + ": " + m_shortDescription + ".\n\"" + what + "\" does not have a prototype";
} //CompassAnalyses::FunctionDefinitionPrototype::CheckerOutput::getString()
示例#8
0
AST_Graph::nodePartOfGraph::result_type
AST_Graph::nodePartOfGraph::operator()(pair<SgNode*,std::string>& x)
   {
     result_type functionalReturn;
     functionalReturn.addToGraph = true;
     functionalReturn.DOTOptions = "";
     functionalReturn.DOTLabel      = "";
     
     SgLocatedNode* locatedNode = isSgLocatedNode(x.first);
     if(locatedNode!=NULL)
        {
          Sg_File_Info* fileInfo = locatedNode->get_file_info();
          std::string filename(Rose::utility_stripPathFromFileName(fileInfo->get_filename()));

          if (filename.find("rose_edg_required_macros_and_functions.h") != std::string::npos)
             {
               functionalReturn.addToGraph = false;
             }

          if (fileInfo->isCompilerGenerated()==true)
             {
            // std::cout << "Is compiler generated\n";
               functionalReturn.addToGraph = false;
             }
        }
           
     return functionalReturn;
   }
 void visit(SgNode *node) {
     SgLocatedNode *located = isSgLocatedNode(node);
     if (located) {
         fix(located, located->get_file_info());
         fix(located, located->generateMatchingFileInfo());
         fix(located, located->get_startOfConstruct());
         fix(located, located->get_endOfConstruct());
     }
 }
示例#10
0
void
WalrusGraph::Counter::visit ( SgNode* astNode )
   {
     SgLocatedNode* locatedNode = isSgLocatedNode(astNode);
     if ( (isBinary == true) || (locatedNode != NULL && locatedNode->get_file_info()->isFrontendSpecific() == false))
        {
          node_to_index_map[astNode] = counter++;
        }
   }
               void visit ( SgNode* astNode )
                  {
                    SgLocatedNode* locatedNode = isSgLocatedNode(astNode);
                    if (locatedNode != NULL)
                       {
                         locatedNode->get_file_info()->setTransformation();
                         locatedNode->get_file_info()->setOutputInCodeGeneration();

                      // Uncomment to see the source position information for each SgLocatedNode IR node.
                      // locatedNode->get_file_info()->display("markAsTransformation(): debug");
                       }
                  }
SynthesizedAttribute
visitorTraversal::evaluateSynthesizedAttribute ( SgNode* n, SynthesizedAttributesList childAttributes )
   {
     SynthesizedAttribute localResult;

  // printf ("In evaluateSynthesizedAttribute(n = %p = %s) \n",n,n->class_name().c_str());

  // Build the list from children (in reverse order to preserve the final ordering)
     for (SynthesizedAttributesList::reverse_iterator child = childAttributes.rbegin(); child != childAttributes.rend(); child++)
        {
          localResult.accumulatedList.splice(localResult.accumulatedList.begin(),child->accumulatedList);
        }

  // Add in the information from the current node
     SgLocatedNode* locatedNode = isSgLocatedNode(n);
     if (locatedNode != NULL)
        {
          AttachedPreprocessingInfoType* commentsAndDirectives = locatedNode->getAttachedPreprocessingInfo();

          if (commentsAndDirectives != NULL)
             {
            // printf ("Found attached comments (to IR node at %p of type: %s): \n",locatedNode,locatedNode->class_name().c_str());
            // int counter = 0;

            // Use a reverse iterator so that we preserve the order when using push_front to add each directive to the accumulatedList
               AttachedPreprocessingInfoType::reverse_iterator i;
               for (i = commentsAndDirectives->rbegin(); i != commentsAndDirectives->rend(); i++)
                  {
                 // The different classifications of comments and directives are in ROSE/src/frontend/SageIII/rose_attributes_list.h
                    if ((*i)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorDefineDeclaration)
                       {
#if 0
                         printf ("          Attached Comment #%d in file %s (relativePosition=%s): classification %s :\n%s\n",
                            counter++,(*i)->get_file_info()->get_filenameString().c_str(),
                            ((*i)->getRelativePosition() == PreprocessingInfo::before) ? "before" : "after",
                            PreprocessingInfo::directiveTypeName((*i)->getTypeOfDirective()).c_str(),
                            (*i)->getString().c_str());
#endif
                      // use push_front() to end up with source ordering of final list of directives
                         localResult.accumulatedList.push_front(*i);
                       }
                  }
             }
        }

  // printf ("localResult after adding current node info \n");
  // localResult.display();

     return localResult;
   }
示例#13
0
static std::string
commentAndCppInformation (SgNode* node)
   {
  // DQ (8/31/2013): Adding source position information for DOT output.
     string ss;

     SgLocatedNode* locatedNode = isSgLocatedNode(node);
     if (locatedNode != NULL)
        {
          AttachedPreprocessingInfoType* commentsAndCppDirectives = locatedNode->getAttachedPreprocessingInfo();
          size_t numberofCommentsAndCppDirectives = 0;
          if (commentsAndCppDirectives != NULL)
             {
               numberofCommentsAndCppDirectives = commentsAndCppDirectives->size();
               if (numberofCommentsAndCppDirectives >= 0)
                  {
                 // ss = string("comments = ") + StringUtility::numberToString(numberofCommentsAndCppDirectives) + "\\n";
                    ss += string("comments/directives (before) = ") + StringUtility::numberToString(numberByRelativePosition(commentsAndCppDirectives,PreprocessingInfo::before)) + "\\n";
                    ss += string("comments/directives (inside) = ") + StringUtility::numberToString(numberByRelativePosition(commentsAndCppDirectives,PreprocessingInfo::inside)) + "\\n";
                    ss += string("comments/directives (after)  = ") + StringUtility::numberToString(numberByRelativePosition(commentsAndCppDirectives,PreprocessingInfo::after)) + "\\n";
                  }
             }
        }

#if 0
       else
        {
       // DQ (9/1/2013): We could handle the source position of some other IR nodes (e.g. output name of the file for SgFile).
          SgFile* file = isSgFile(node);
          if (file != NULL)
             {
            // ROSE_ASSERT(file->get_file_info() != NULL);
            // ss += generateFileLineColumnString(file->get_file_info());
               AttachedPreprocessingInfoType* commentsAndCppDirectives = file->getAttachedPreprocessingInfo();
               size_t numberofCommentsAndCppDirectives = 0;
               if (commentsAndCppDirectives != NULL)
                  {
                    numberofCommentsAndCppDirectives = commentsAndCppDirectives->size();
                    if (numberofCommentsAndCppDirectives > 0)
                       {
                         ss = string("comments = ") + StringUtility::numberToString(numberofCommentsAndCppDirectives) + "\\n";
                       }
                  }
             }
        }
#endif

     return ss;
   }
示例#14
0
 source_position roseNode::getEndPos() const
 {
   source_position pos; 
   ROSE_ASSERT(mNode!=NULL);
   SgLocatedNode* lnode = isSgLocatedNode(mNode);
   if (lnode != NULL)
   {  
     pos.line = lnode->get_endOfConstruct()->get_line();
     pos.column= lnode->get_endOfConstruct()->get_col(); 
   }else
   {
     pos.line=0;
     pos.column=0;
   }
   return pos;
 }
示例#15
0
//The argument to the function is 
filterOnNodes::result_type
filterOnNodes::operator()(filterOnNodes::argument_type x) const
   {
     AST_Graph::FunctionalReturnType returnValue;
     //Determine if the node is to be added to the graph. true=yes
     returnValue.addToGraph = true;
     //set colors etc. for the graph Node
     returnValue.DOTOptions = "shape=polygon,regular=0,URL=\"\\N\",tooltip=\"more info at\\N\",sides=4,peripheries=1,color=\"Blue\",fillcolor=green,fontname=\"7x13bold\",fontcolor=black,style=filled";

     if( isSgProject(x.first) != NULL )
        returnValue.DOTOptions = "shape=ellipse,regular=0,URL=\"\\N\",tooltip=\"more info at\\N\",sides=4,peripheries=1,color=\"Blue\",fillcolor=yellow,fontname=\"7x13bold\",fontcolor=black,style=filled";



     //Filter out SgSymbols from the graph
     if ( isSgSymbol(x.first) != NULL )
          returnValue.addToGraph = false;

     if ( isSgType(x.first) != NULL )
          returnValue.addToGraph = false;

     //Filter out compiler generated nodes
     SgLocatedNode* locatedNode = isSgLocatedNode(x.first);
     if ( locatedNode != NULL )
        {
          Sg_File_Info* fileInfo = locatedNode->get_file_info();
          std::string filename(Rose::utility_stripPathFromFileName(fileInfo->get_filename()));



          if (filename.find("rose_edg_macros_and_functions_required_for_gnu.h") != std::string::npos)
             {
               returnValue.addToGraph = false;
             }

          if (fileInfo->isCompilerGenerated()==true)
             {
            // std::cout << "Is compiler generated\n";
               returnValue.addToGraph = false;
             }
        }

     return returnValue;
   }
示例#16
0
  string roseNode::getFileName() const
  {
    string result;
    ROSE_ASSERT(mNode!=NULL);
    // no uniform way to get file name in ROSE
    SgLocatedNode* lnode = isSgLocatedNode(mNode);
    SgSourceFile* sfile = isSgSourceFile(mNode);
    if (lnode)
      result = lnode->getFilenameString();
    else if (sfile)
      result = sfile->getFileName();
    else
    {
      cerr<<"error: unrecognized sage node to get a file name:"
        <<mNode->class_name()<<endl;
      ROSE_ASSERT(false);
    }

    return result;
  }
示例#17
0
string
AstPDFGeneration_private::get_bookmark_name(SgNode* node)
   {
     string nodefilename="--not initialized--";
     string bookmarktext;
        {
          ostringstream ss;
          ss << node->sage_class_name() << " ";
          SgLocatedNode* sgLocNode = dynamic_cast<SgLocatedNode*> (node);
          if(sgLocNode)
             {
               Sg_File_Info* fi = sgLocNode->get_file_info();
               if(fi)
                  {
                 // ss << "(" << fi->get_line() << "," << fi->get_col() << ") in \"" << fi->get_filename() << "\"";
                 // nodefilename=string(fi->get_filename());
#if 1      
                //  if (fi->isCompilerGenerated())
                //    ss << " compilerGenerated "; 
                  if (fi->isTransformation())
                      ss << " transformation " ;
                  if (fi->isOutputInCodeGeneration())   
                       ss<< " unparsable ";
                    ss << "(" << fi->get_line() << "," << fi->get_col() << ") in \"" << fi->get_filename() << "\"";
#endif                       
                    nodefilename=string(fi->get_filename());
                  }
                 else
                  {
                    ss << "(BUG)";
                  }
             }
            else
             {
               ss << ""; // provide no explicit info about the lack of file_info
             }
          bookmarktext=ss.str();
        }

      return bookmarktext;
   }
示例#18
0
std::string
Compass::OutputViolationBase::getString() const
{
  ROSE_ASSERT(getNodeArray().size() <= 1);

  // Default implementation for getString
  SgLocatedNode* locatedNode = isSgLocatedNode(getNode());
  std::string sourceCodeLocation;
  if (locatedNode != NULL)
    {
      Sg_File_Info* start = locatedNode->get_startOfConstruct();
      Sg_File_Info* end   = locatedNode->get_endOfConstruct();
      sourceCodeLocation = (end ? Compass::formatStandardSourcePosition(start, end) 
			    : Compass::formatStandardSourcePosition(start));
    }
  else
    {
      // Else this could be a SgInitializedName or SgTemplateArgument (not yet moved to be a SgLocatedNode)
      if (getNode()) {
  //      std::cerr << "Node : " << getNode()->class_name() << std::endl;
        Sg_File_Info* start = getNode()->get_file_info();
      // tps : 22Jan 2009 - commented the following out because it does not work with binaries
      //ROSE_ASSERT(start != NULL);
        if (start)
	  sourceCodeLocation = Compass::formatStandardSourcePosition(start);
      }
    }

  // tps Jan 23 2009: getNode() can be NULL because it could be a binary node
  // added a test for this
  std::string nodeName = "unknown";
	if (getNode())
            getNode()->class_name();

  // The short description used here needs to be put into a separate function (can this be part of what is filled in by the script?)
  // return loc + ": " + nodeName + ": variable requiring static constructor initialization";

  // return m_checkerName + ": " + sourceCodeLocation + ": " + nodeName + ": " + m_shortDescription;
  return m_checkerName + ": " + sourceCodeLocation + ": " + m_shortDescription;
}
 // Start marking nodes as frontend-specific once we enter an AST that's frontend-specific.
 void preOrderVisit(SgNode *node) {
     SgLocatedNode *located = isSgLocatedNode(node);
     if (located) {
         bool in_fes_ast = fes_ast!=NULL ||
                           is_frontend_specific(located->get_file_info()) ||
                           is_frontend_specific(located->generateMatchingFileInfo()) ||
                           is_frontend_specific(located->get_startOfConstruct()) ||
                           is_frontend_specific(located->get_endOfConstruct());
         if (in_fes_ast) {
             if (!fes_ast)
                 fes_ast = node;
             fix(located, located->get_file_info());
             fix(located, located->generateMatchingFileInfo());
             fix(located, located->get_startOfConstruct());
             fix(located, located->get_endOfConstruct());
         }
     }
 }
void
visitorTraversal::visit (SgNode * n)
{
  // On each node look for any comments of CPP directives
  SgLocatedNode *locatedNode = isSgLocatedNode (n);
  if (locatedNode != NULL)
  {
    AttachedPreprocessingInfoType *comments =
      locatedNode->getAttachedPreprocessingInfo ();

    if (comments != NULL)
    {
      printf ("-----------------------------------------------\n");
      printf ("Found an IR node with preprocessing Info attached:\n");
      printf ("(memory address: %p Sage type: %s) in file \n%s (line %d column %d) \n",
          locatedNode, 
          locatedNode->class_name ().c_str (),
          (locatedNode->get_file_info ()->get_filenameString ()).c_str (),
          locatedNode->get_file_info ()->get_line(),
          locatedNode->get_file_info ()->get_col()         );
      int counter = 0;
      AttachedPreprocessingInfoType::iterator i;
      for (i = comments->begin (); i != comments->end (); i++)
      {
        printf("-------------PreprocessingInfo #%d ----------- : \n",counter++);
        printf("classification = %s:\n String format = %s\n",
                PreprocessingInfo::directiveTypeName((*i)->getTypeOfDirective ()). c_str (), 
                (*i)->getString ().c_str ());
        printf ("relative position is = ");
        if ((*i)->getRelativePosition () == PreprocessingInfo::inside)
          printf ("inside\n");
        else
          printf ("%s\n", \
              ((*i)->getRelativePosition () == PreprocessingInfo::before) ? "before" : "after");
      }
    }
  }
}
示例#21
0
void 
AstPDFGeneration_private::edit_page(size_t pageNumber, SgNode* node, PDFInheritedAttribute inheritedValue)
{
  // JW (added by DQ 7/23/2004): Adds address of each IR node to the top of the page
  HPDF_Page_SetRGBFill(currentPage, 1, 0, 0);
  // DQ (1/20/2006): Modified for 64 bit machines
  // ostringstream _ss; _ss << "0x" << std::hex << (int)node;
  ostringstream _ss; 
  _ss << "pointer:" << std::hex << node;
  HPDF_Page_ShowTextNextLine(currentPage, _ss.str().c_str());

  // Liao, 2/11/2009, move some essential information from bookmark into the page also
  // since some deep levels of bookmarks cannot display long lines properly by acrobat reader
  HPDF_Page_ShowTextNextLine(currentPage, node->sage_class_name());
  SgLocatedNode* sgLocNode = dynamic_cast<SgLocatedNode*> (node);
  if(sgLocNode)
  {
    Sg_File_Info* fi = sgLocNode->get_file_info();
    ostringstream temp;
    temp<<fi->get_filename()<<" "<<fi->get_line()<<":"<<fi->get_col();
    if(fi)
      HPDF_Page_ShowTextNextLine(currentPage,temp.str().c_str());
    if (fi->isTransformation()) 
      HPDF_Page_ShowTextNextLine(currentPage,"IsTransformation:1");
    else
      HPDF_Page_ShowTextNextLine(currentPage,"IsTransformation:0");

    if (fi->isOutputInCodeGeneration())   
      HPDF_Page_ShowTextNextLine(currentPage,"IsOutputInCodeGeneration:1");
    else        
      HPDF_Page_ShowTextNextLine(currentPage,"IsOutputInCodeGeneration:0");

  }
  if (isSgDeclarationStatement(node))
  {
    HPDF_Page_ShowTextNextLine(currentPage, ("Declaration mangled name: " + isSgDeclarationStatement(node)->get_mangled_name().getString()).c_str());
#if 0  // not necessary, p_name field gives the similar information   
    if (isSgDeclarationStatement(node)->hasAssociatedSymbol())
    {
      SgSymbol *symbol = isSgDeclarationStatement(node)->get_symbol_from_symbol_table ();
      if (symbol)
        HPDF_Page_ShowTextNextLine(currentPage, ("Symbol name: " + symbol->get_name().getString()).c_str());
    }
#endif    
 }


  // JW hack to show expression types
  if (isSgExpression(node))
    HPDF_Page_ShowTextNextLine(currentPage, ("Expression type: " + isSgExpression(node)->get_type()->unparseToString()).c_str());

  HPDF_Page_SetRGBFill(currentPage, 0, 1, 0);

  if (inheritedValue.parentPage==NULL)
  {
    HPDF_Page_ShowTextNextLine(currentPage, "");
    HPDF_Page_ShowTextNextLine(currentPage, "      root node");
  }
  else
  {
    HPDF_Page_ShowTextNextLine(currentPage, "");
    HPDF_Page_ShowTextNextLine(currentPage, "     ");
    create_textlink("Click here to go to the parent node", inheritedValue.parentPage, 9);
  }
  HPDF_Page_ShowTextNextLine(currentPage, "");
  HPDF_Page_ShowTextNextLine(currentPage, "");

  // generate RTI information for SgNode
  {
    RTIReturnType rti=node->roseRTI();
    for(RTIReturnType::iterator i=rti.begin(); i<rti.end(); i++)
    {
      if (strlen(i->type) >= 7 &&
          strncmp(i->type, "static ", 7) == 0) {
        continue; // Skip static members
      }
      HPDF_Page_SetRGBFill(currentPage, 0.5, 0, 0.1);
      HPDF_Page_ShowTextNextLine(currentPage, i->type);
      HPDF_Page_ShowText(currentPage, " ");
      HPDF_Page_SetRGBFill(currentPage, 0.0, 0.5, 0.5);
      HPDF_Page_ShowText(currentPage, i->name);
      HPDF_Page_ShowText(currentPage, " : ");
      HPDF_Page_SetRGBFill(currentPage, 0.0, 0.0, 0.0);

      string value=i->value;
      if (value.size() >= 80) { // HPDF doesn't like strings > 64k, and we probably shouldn't be trying to print them anyway; this trims things to a reasonable length
        value = "<too long>: " + value.substr(0, 80);
      }
      if (value.size() >= 80) {
        value = "<too long>: " + value.substr(0, 80);
      }
      AstNodeVisitMapping::MappingType::iterator mapit;

      // ensure that mapping value exists (otherwise it would be added to the map)
      // and decide whether to create a link to a page (representing a node) or not
      mapit=addrPageMapping.find(value);
      if (mapit!=addrPageMapping.end())
      {
        size_t destPageNum = mapit->second;
        ROSE_ASSERT (destPageNum < pageDests.size());
        create_textlink(value.c_str(), pageDests[destPageNum] /* targetpage */);
      }
      else 
      {
        HPDF_Page_ShowText(currentPage,value.c_str());
      }
    }
  }

  // generate AstAttribute information
  {
    // printf ("In AstPDFGeneration_private::edit_page(): using new attribute interface \n");
    // if (node->get_attribute() != NULL)
#if 0
    if (node->getAttribute() != NULL)
    {
      AstAttributeMechanism::AttributeIdentifiers aidents = node->attribute().getAttributeIdentifiers();
      PDF_continue_text(pdfFile, ""); // next line
      PDF_setrgbcolor(pdfFile, 0.0, 0.2, 0.7);
      PDF_continue_text(pdfFile, "AstAttributes:"); // next line
      for (AstAttributeMechanism::AttributeIdentifiers::iterator it = aidents.begin(); it != aidents.end(); it++)
      {
        PDF_continue_text(pdfFile, ""); // next line
        PDF_setrgbcolor(pdfFile, 0.0, 0.2, 0.7);
        PDF_show(pdfFile,((*it)+": ").c_str());
        PDF_setrgbcolor(pdfFile, 0.0, 0.0, 0.0);
        // float textxpos=PDF_get_value(pdfFile,"textx",0.0);
        // float textypos=PDF_get_value(pdfFile,"texty",0.0); 
        string attributeValue = (node->attribute()[*it])->toString();

        // split string into different substrings separated by newlines
        string substring="";
        int oldpos=0;
        int newpos;
        do {
          newpos=attributeValue.find('\n', oldpos);
          substring=attributeValue.substr(oldpos,newpos-oldpos);
          if(oldpos==0)
            PDF_show(pdfFile, substring.append("   ").c_str());
          else
            PDF_continue_text(pdfFile, substring.c_str());
          oldpos = newpos+1; // go to next '\n' and skip it
        }
        // DQ (8/9/2005): Suggested fix from Rich (fixes infinite loop where AST Attributes are attached)
        // while( newpos < (int) attributeValue.size());
        while( newpos < (int) attributeValue.size() && newpos >= 0 );
        // PDF_show_boxed(pdfFile, attributeValue.c_str(), textxpos, textypos, 0, 0, "left", "");
      }
    }
#else
    // DQ (4/10/2006): New AstAttribute Interface (but access the AstAttributeMechanism directly 
    // since "getAttributeIdentifiers()" is not in the interface implemented at the IR nodes).
    if (node->get_attributeMechanism() != NULL)
    {
      AstAttributeMechanism::AttributeIdentifiers aidents = node->get_attributeMechanism()->getAttributeIdentifiers();
      HPDF_Page_ShowTextNextLine(currentPage, ""); // next line
      HPDF_Page_SetRGBFill(currentPage, 0.0, 0.2, 0.7);
      HPDF_Page_ShowTextNextLine(currentPage, "AstAttributes:"); // next line
      for (AstAttributeMechanism::AttributeIdentifiers::iterator it = aidents.begin(); it != aidents.end(); it++)
      {
        HPDF_Page_ShowTextNextLine(currentPage, ""); // next line
        HPDF_Page_SetRGBFill(currentPage, 0.0, 0.2, 0.7);
        HPDF_Page_ShowText(currentPage,((*it)+": ").c_str());
        HPDF_Page_SetRGBFill(currentPage, 0.0, 0.0, 0.0);
        // float textxpos=PDF_get_value(pdfFile,"textx",0.0);
        // float textypos=PDF_get_value(pdfFile,"texty",0.0); 
        // string attributeValue = (node->attribute()[*it])->toString();
        string attributeValue = node->getAttribute(*it)->toString();

        // split string into different substrings separated by newlines
        string substring="";
        int oldpos=0;
        int newpos;
        do {
          newpos=attributeValue.find('\n', oldpos);
          substring=attributeValue.substr(oldpos,newpos-oldpos);
          if(oldpos==0)
            HPDF_Page_ShowText(currentPage, substring.append("   ").c_str());
          else
            HPDF_Page_ShowTextNextLine(currentPage, substring.c_str());
          oldpos = newpos+1; // go to next '\n' and skip it
        }
        // DQ (8/9/2005): Suggested fix from Rich (fixes infinite loop where AST Attributes are attached)
        // while( newpos < (int) attributeValue.size());
        while( newpos < (int) attributeValue.size() && newpos >= 0 );
        // PDF_show_boxed(pdfFile, attributeValue.c_str(), textxpos, textypos, 0, 0, "left", "");
      }
    } // end if 
#endif
  }

}
示例#22
0
SgClassDeclaration* RtedTransformation::instrumentClassDeclarationIntoTopOfAllSourceFiles(
      SgProject* project, SgClassDeclaration* classDecl) {
   // **********************
   if (RTEDDEBUG) cerr <<"@@@ instrumenting into top "<< endl;
   // deep copy the classdecl and make it unparseable
   SgClassDeclaration* cd_copy = SageInterface::deepCopy(classDecl);
   // cout << ">>>>>> Original ClassType :::: " << classDecl->get_type() << endl;
   // cout << ">>>>>> Copied ClassType :::: " << cd_copy->get_type() << endl;
   // SgClassType* type_copy = new SgClassType(cd_copy);
   //cd_copy->set_type(type_copy);
   ROSE_ASSERT(cd_copy);
   const SgNodePtrList&          nodes2 = NodeQuery::querySubTree(cd_copy, V_SgLocatedNode);
   SgNodePtrList::const_iterator nodesIT2 = nodes2.begin();
   for (; nodesIT2 != nodes2.end(); ++nodesIT2) {
      SgLocatedNode* node = isSgLocatedNode(*nodesIT2);
      ROSE_ASSERT(node);
      Sg_File_Info* file_info = node->get_file_info();
      file_info->setOutputInCodeGeneration();
      //cerr << "copying node : " << node->class_name() << endl;
   }
   if (RTEDDEBUG) cerr << "deep copy of firstnondefining" << endl;

   SgClassDeclaration* nondefDecl = isSgClassDeclaration(classDecl->get_firstNondefiningDeclaration());
   SgClassDeclaration* cdn_copy = SageInterface::deepCopy(nondefDecl);
   ROSE_ASSERT(cdn_copy);

   const SgNodePtrList&          nodes = NodeQuery::querySubTree(cdn_copy, V_SgLocatedNode);
   SgNodePtrList::const_iterator nodesIT = nodes.begin();
   for (; nodesIT != nodes.end(); ++nodesIT) {
      SgLocatedNode* node = isSgLocatedNode(*nodesIT);
      ROSE_ASSERT(node);
      Sg_File_Info* file_info = node->get_file_info();
      file_info->setOutputInCodeGeneration();
   }
   cd_copy->set_firstNondefiningDeclaration(cdn_copy);
   SgClassType* cls_type = SgClassType::createType(cdn_copy);
   cls_type->set_declaration(cdn_copy);
   ROSE_ASSERT(cls_type != NULL);
   ROSE_ASSERT (cls_type->get_declaration() == cdn_copy);
   cdn_copy->set_type(cls_type);
   cdn_copy->set_definingDeclaration(cd_copy);
   cd_copy->set_type(cdn_copy->get_type());

   if (RTEDDEBUG) {
      cerr << "@@@@@@@@@@@@@@ Original Class classDecl : " << classDecl << " :: " << cd_copy << endl;
      cerr << "@@@@@@@@@@@@@@ Original Class nondefining : " << classDecl->get_firstNondefiningDeclaration()<< " :: " << cdn_copy << endl;
      cerr << "@@@@@@@@@@@@@@@@@@ TYPE OF cd_copy->get_type() : " << cd_copy->get_type() << endl;
      cerr << "@@@@@@@@@@@@@@@@@@ TYPE OF cdn_copy->get_type() : " <<  cdn_copy->get_type() << endl;

      cerr << "@@@@@@@@@@@@@@@@@@ TYPE OF cd_copy->get_type()->declaration : " <<cd_copy->get_type()->get_declaration() << endl;
      cerr << "@@@@@@@@@@@@@@@@@@ TYPE OF cd_copy->definingDeclaration : " <<   cd_copy->get_definingDeclaration() << endl;
      cerr << "@@@@@@@@@@@@@@@@@@ TYPE OF cd_copy->set_firstNondefiningDeclaration : " <<   cd_copy->get_firstNondefiningDeclaration() << endl;
   }
   // **********************
   // add to top of each source file

   // insert at top of all source files in reverse order
   // only if the class has private members and if it is declared in a header file
   std::vector<SgSourceFile*>::const_iterator aa = srcfiles.begin();
   std::vector<SgSourceFile*>::const_iterator zz = srcfiles.end();
   for (; aa != zz; ++aa)
   {
      SgSourceFile* sf = *aa;
      assert( isInInstrumentedFile(sf) );

      if (RTEDDEBUG) cerr << "Looking through sourcefile: " << sf -> get_file_info() -> get_filename() << endl;
      // once we have the new class_decl inserted, we remove all functions and the constructor and destructor
      const SgNodePtrList&          remNodes = NodeQuery::querySubTree(cd_copy, V_SgFunctionDeclaration);
      SgNodePtrList::const_iterator remNodesIt = remNodes.begin();
      for (; remNodesIt != remNodes.end(); ++remNodesIt) {
        SgFunctionDeclaration* node = isSgFunctionDeclaration(*remNodesIt);
        ROSE_ASSERT(node);
        SageInterface::removeStatement(node);
      }

      if (RTEDDEBUG) cerr << "  changing privates to public" << endl;
      // change each private: to public:
      SgClassDefinition* cd_def = cd_copy->get_definition();
      ROSE_ASSERT(cd_def);
      SgDeclarationStatementPtrList decls = cd_def->get_members();
      SgDeclarationStatementPtrList::const_iterator itDecls = decls.begin();
      for (;itDecls!=decls.end();++itDecls) {
        SgVariableDeclaration* node = isSgVariableDeclaration(*itDecls);
        if (node) {
           SgDeclarationModifier& mod = node->get_declarationModifier();
           SgAccessModifier& am = mod.get_accessModifier();
           if (am.isPrivate() || am.isProtected())
              am.setPublic();
        }
      }

      // get the namespace RTED to put new class into
      if (RTEDDEBUG) cerr << "Finding Namespace RTED  "  <<  endl;

      SourceFileRoseNMType::const_iterator pit = sourceFileRoseNamespaceMap.find(sf);
      ROSE_ASSERT(pit!=sourceFileRoseNamespaceMap.end());

      SgNamespaceDeclarationStatement* firstNamespace = pit->second;

      // insert at top of file - after includes
      if (RTEDDEBUG)
      {
         cerr << " Prepending to source file: " << sf -> get_file_info() -> get_filename()
              << "   class : " << cd_copy->get_name().str()
              << endl;
      }

      // we prepend it to the top of the file and later move the include back up
      SageInterface::prependStatement(cdn_copy,firstNamespace->get_definition());
      SageInterface::appendStatement(cd_copy, firstNamespace->get_definition() );

      ROSE_ASSERT(cdn_copy->get_symbol_from_symbol_table() != NULL);
      classesInRTEDNamespace[classDecl->get_definition()] = cd_def;
   }

   return cd_copy;
}
示例#23
0
文件: unparser.C 项目: 8l/rose
string globalUnparseToString ( SgNode* astNode, SgUnparse_Info* inputUnparseInfoPointer )
{
  // This global function permits any SgNode (including it's subtree) to be turned into a string

  // DQ (3/2/2006): Let's make sure we have a valid IR node!
     ROSE_ASSERT(astNode != NULL);

     string returnString;

  // all options are now defined to be false. When these options can be passed in
  // from the prompt, these options will be set accordingly.
     bool _auto                         = false;
     bool linefile                      = false;
     bool useOverloadedOperators        = false;
     bool num                           = false;

  // It is an error to have this always turned off (e.g. pointer = this; will not unparse correctly)
     bool _this                         = true;

     bool caststring                    = false;
     bool _debug                        = false;
     bool _class                        = false;
     bool _forced_transformation_format = false;
     bool _unparse_includes             = false;

  // printf ("In globalUnparseToString(): astNode->sage_class_name() = %s \n",astNode->sage_class_name());

     Unparser_Opt roseOptions( _auto,
                               linefile,
                               useOverloadedOperators,
                               num,
                               _this,
                               caststring,
                               _debug,
                               _class,
                               _forced_transformation_format,
                               _unparse_includes );

     int lineNumber = 0;  // Zero indicates that ALL lines should be unparsed

     // Initialize the Unparser using a special string stream inplace of the usual file stream 
     ostringstream outputString;

     SgLocatedNode* locatedNode = isSgLocatedNode(astNode);
     string fileNameOfStatementsToUnparse;
     if (locatedNode == NULL)
        {
       // printf ("WARNING: applying AST -> string for non expression/statement AST objects \n");
          fileNameOfStatementsToUnparse = "defaultFileNameInGlobalUnparseToString";
        }
       else
        {
          ROSE_ASSERT (locatedNode != NULL);

       // DQ (5/31/2005): Get the filename from a traversal back through the parents to the SgFile
       // fileNameOfStatementsToUnparse = locatedNode->getFileName();
       // fileNameOfStatementsToUnparse = rose::getFileNameByTraversalBackToFileNode(locatedNode);
          if (locatedNode->get_parent() == NULL)
             {
            // DQ (7/29/2005):
            // Allow this function to be called with disconnected AST fragments not connected to 
            // a previously generated AST.  This happens in Qing's interface where AST fragements 
            // are built and meant to be unparsed.  Only the parent of the root of the AST 
            // fragement is expected to be NULL.
               fileNameOfStatementsToUnparse = locatedNode->getFileName();
             }
            else
             {
               fileNameOfStatementsToUnparse = rose::getFileNameByTraversalBackToFileNode(locatedNode);
             }
          
        }
     ROSE_ASSERT (fileNameOfStatementsToUnparse.size() > 0);

     Unparser roseUnparser ( &outputString, fileNameOfStatementsToUnparse, roseOptions, lineNumber );

  // Information that is passed down through the tree (inherited attribute)
  // Use the input SgUnparse_Info object if it is available.
     SgUnparse_Info* inheritedAttributeInfoPointer = NULL;
     if (inputUnparseInfoPointer != NULL)
        {
       // printf ("Using the input inputUnparseInfoPointer object \n");

       // Use the user provided SgUnparse_Info object
          inheritedAttributeInfoPointer = inputUnparseInfoPointer;
        }
       else
        {
       // DEFINE DEFAULT BEHAVIOUR FOR THE CASE WHEN NO inputUnparseInfoPointer (== NULL) IS 
       // PASSED AS ARGUMENT TO THE FUNCTION
       // printf ("Building a new Unparse_Info object \n");

       // If no input parameter has been specified then allocate one
       // inheritedAttributeInfoPointer = new SgUnparse_Info (NO_UNPARSE_INFO);
          inheritedAttributeInfoPointer = new SgUnparse_Info();
          ROSE_ASSERT (inheritedAttributeInfoPointer != NULL);

       // MS: 09/30/2003: comments de-activated in unparsing
          ROSE_ASSERT (inheritedAttributeInfoPointer->SkipComments() == false);

       // Skip all comments in unparsing
          inheritedAttributeInfoPointer->set_SkipComments();
          ROSE_ASSERT (inheritedAttributeInfoPointer->SkipComments() == true);
       // Skip all whitespace in unparsing (removed in generated string)
          inheritedAttributeInfoPointer->set_SkipWhitespaces();
          ROSE_ASSERT (inheritedAttributeInfoPointer->SkipWhitespaces() == true);

       // Skip all directives (macros are already substituted by the front-end, so this has no effect on those)
          inheritedAttributeInfoPointer->set_SkipCPPDirectives();
          ROSE_ASSERT (inheritedAttributeInfoPointer->SkipCPPDirectives() == true);
        }

     ROSE_ASSERT (inheritedAttributeInfoPointer != NULL);
     SgUnparse_Info & inheritedAttributeInfo = *inheritedAttributeInfoPointer;

  // Turn ON the error checking which triggers an error if the default SgUnparse_Info constructor is called
  // SgUnparse_Info::forceDefaultConstructorToTriggerError = true;

#if 1
  // DQ (10/19/2004): Cleaned up this code, remove this dead code after we are sure that this worked properly
  // Actually, this code is required to be this way, since after this branch the current function returns and
  // some data must be cleaned up differently!  So put this back and leave it this way, and remove the
  // "Implementation Note".

  // Both SgProject and SgFile are handled via recursive calls
     if ( (isSgProject(astNode) != NULL) || (isSgFile(astNode) != NULL) )
        {
       // printf ("Implementation Note: Put these cases (unparsing the SgProject and SgFile into the cases for nodes derived from SgSupport below! \n");

       // Handle recursive call for SgProject
          if (isSgProject(astNode) != NULL)
             {
               SgProject* project = isSgProject(astNode);
               ROSE_ASSERT(project != NULL);
               for (int i = 0; i < project->numberOfFiles(); i++)
                  {
                    SgFile* file = &(project->get_file(i));
                    ROSE_ASSERT(file != NULL);
                    string unparsedFileString = globalUnparseToString(file,inputUnparseInfoPointer);
                    string prefixString       = string("/* TOP:")      + string(rose::getFileName(file)) + string(" */ \n");
                    string suffixString       = string("\n/* BOTTOM:") + string(rose::getFileName(file)) + string(" */ \n\n");
                    returnString += prefixString + unparsedFileString + suffixString;
                  }
             }

       // Handle recursive call for SgFile
          if (isSgFile(astNode) != NULL)
             {
               SgFile* file = isSgFile(astNode);
               ROSE_ASSERT(file != NULL);
               SgGlobal* globalScope = file->get_root();
               ROSE_ASSERT(globalScope != NULL);
               returnString = globalUnparseToString(globalScope,inputUnparseInfoPointer);
             }
        }
       else
#endif
        {
       // DQ (1/12/2003): Only now try to trap use of SgUnparse_Info default constructor
       // Turn ON the error checking which triggers an error if the default SgUnparse_Info constructor is called
          SgUnparse_Info::set_forceDefaultConstructorToTriggerError(true);

          if (isSgStatement(astNode) != NULL)
             {
               SgStatement* stmt = isSgStatement(astNode);
               roseUnparser.unparseStatement ( stmt, inheritedAttributeInfo );
             }

          if (isSgExpression(astNode) != NULL)
             {
               SgExpression* expr = isSgExpression(astNode);
               roseUnparser.unparseExpression ( expr, inheritedAttributeInfo );
             }

          if (isSgType(astNode) != NULL)
             {
               SgType* type = isSgType(astNode);
               roseUnparser.unparseType ( type, inheritedAttributeInfo );
             }

          if (isSgSymbol(astNode) != NULL)
             {
               SgSymbol* symbol = isSgSymbol(astNode);
               roseUnparser.unparseSymbol ( symbol, inheritedAttributeInfo );
             }

          if (isSgSupport(astNode) != NULL)
             {
            // Handle different specific cases derived from SgSupport 
            // (e.g. template parameters and template arguments).
               switch (astNode->variantT())
                  {
#if 0
                    case V_SgProject:
                       {
                         SgProject* project = isSgProject(astNode);
                         ROSE_ASSERT(project != NULL);
                         for (int i = 0; i < project->numberOfFiles(); i++)
                            {
                              SgFile* file = &(project->get_file(i));
                              ROSE_ASSERT(file != NULL);
                              string unparsedFileString = globalUnparseToString(file,inputUnparseInfoPointer);
                              string prefixString       = string("/* TOP:")      + string(rose::getFileName(file)) + string(" */ \n");
                              string suffixString       = string("\n/* BOTTOM:") + string(rose::getFileName(file)) + string(" */ \n\n");
                              returnString += prefixString + unparsedFileString + suffixString;
                            }
                         break;
                       }
                    case V_SgFile:
                       {
                         SgFile* file = isSgFile(astNode);
                         ROSE_ASSERT(file != NULL);
                         SgGlobal* globalScope = file->get_root();
                         ROSE_ASSERT(globalScope != NULL);
                         returnString = globalUnparseToString(globalScope,inputUnparseInfoPointer);
                         break;
                       }
#endif
                    case V_SgTemplateParameter:
                       {
                         SgTemplateParameter* templateParameter = isSgTemplateParameter(astNode);
                         roseUnparser.unparseTemplateParameter(templateParameter,inheritedAttributeInfo);
                         break;
                       }
                    case V_SgTemplateArgument:
                       {
                         SgTemplateArgument* templateArgument = isSgTemplateArgument(astNode);
                         roseUnparser.unparseTemplateArgument(templateArgument,inheritedAttributeInfo);
                         break;
                       }
                    case V_SgInitializedName:
                       {
                      // QY: not sure how to implement this
                      // DQ (7/23/2004): This should unparse as a declaration 
                      // (type and name with initializer).
                         break;
                       }

                    case V_Sg_File_Info:
                       {
                      // DQ (5/11/2006): Not sure how or if we shoul implement this
                         break;
                       }

                 // Perhaps the support for SgFile and SgProject shoud be moved to this location?
                    default:
                         printf ("Error: default reached in node derived from SgSupport astNode = %s \n",astNode->sage_class_name());
                         ROSE_ABORT();
                }
             }

       // Turn OFF the error checking which triggers an if the default SgUnparse_Info constructor is called
          SgUnparse_Info::set_forceDefaultConstructorToTriggerError(false);

       // MS: following is the rewritten code of the above outcommented 
       //     code to support ostringstream instead of ostrstream.
          returnString = outputString.str();

       // Call function to tighten up the code to make it more dense
          if (inheritedAttributeInfo.SkipWhitespaces() == true)
             {
               returnString = roseUnparser.removeUnwantedWhiteSpace ( returnString );
             }

       // delete the allocated SgUnparse_Info object
          if (inputUnparseInfoPointer == NULL)
               delete inheritedAttributeInfoPointer;
        }

     return returnString;
   }
示例#24
0
文件: options.C 项目: 8l/rose
void
TransformationSupport::getTransformationOptions ( SgNode* astNode, list<OptionDeclaration> & generatedList, string identifingTypeName )
   {
  // This function searches for variables of type ScopeBasedTransformationOptimization.  Variables
  // of type ScopeBasedTransformationOptimization are used to communicate optimizations from the
  // application to the preprocessor. If called from a project or file object it traverses down to
  // the global scope of the file and searches only the global scope, if called from and other
  // location within the AST it searches the current scope and then traverses the parent nodes to
  // find all enclosing scopes until in reaches the global scope.  At each scope it searches for
  // variables of type ScopeBasedTransformationOptimization.

  // printf ("######################### START OF TRANSFORMATION OPTION QUERY ######################## \n");

     ROSE_ASSERT (astNode != NULL);
     ROSE_ASSERT (identifingTypeName.c_str() != NULL);

#if 0
     printf ("In getTransformationOptions(): astNode->sage_class_name() = %s generatedList.size() = %d \n",
          astNode->sage_class_name(),generatedList.size());
     SgLocatedNode* locatedNode = isSgLocatedNode(astNode);
     if (locatedNode != NULL)
        {
          printf ("          locatedNode->get_file_info()->get_filename() = %s \n",locatedNode->get_file_info()->get_filename());
          printf ("          locatedNode->get_file_info()->get_line() = %d \n",locatedNode->get_file_info()->get_line());
        }
#endif

     switch (astNode->variant())
        {
          case ProjectTag:
             {
               SgProject* project = isSgProject(astNode);
               ROSE_ASSERT (project != NULL);

           //! Loop through all the files in the project and call the mainTransform function for each file
               int i = 0;
               for (i=0; i < project->numberOfFiles(); i++)
                  {
                    SgFile* file = &(project->get_file(i));

                 // printf ("Calling Query::traverse(SgFile,QueryFunctionType,QueryAssemblyFunctionType) \n");
                    getTransformationOptions ( file, generatedList, identifingTypeName );
                  }
               break;
             }

          case SourceFileTag:
             {
               SgSourceFile* file = isSgSourceFile(astNode);
               ROSE_ASSERT (file != NULL);
               SgGlobal* globalScope = file->get_globalScope();
               ROSE_ASSERT (globalScope != NULL);
               ROSE_ASSERT (isSgGlobal(globalScope) != NULL);
               getTransformationOptions ( globalScope, generatedList, identifingTypeName );
               break;
             }

       // Global Scope
          case GLOBAL_STMT:
             {
               SgGlobal* globalScope = isSgGlobal(astNode);
               ROSE_ASSERT (globalScope != NULL);

               SgSymbolTable* symbolTable = globalScope->get_symbol_table();
               ROSE_ASSERT (symbolTable != NULL);
               getTransformationOptions ( symbolTable, generatedList, identifingTypeName );

            // printf ("Processed global scope, exiting .. \n");
            // ROSE_ABORT();
               break;
             }

          case SymbolTableTag:
             {
            // List the variable in each scope
            // printf ("List all the variables in this symbol table! \n");
               SgSymbolTable* symbolTable = isSgSymbolTable(astNode);
               ROSE_ASSERT (symbolTable != NULL);

               bool foundTransformationOptimizationSpecifier = false;

            // printf ("Now print out the information in the symbol table for this scope: \n");
            // symbolTable->print();

#if 0
            // I don't know when a SymbolTable is given a name!
               printf ("SymbolTable has a name = %s \n",
                    (symbolTable->get_no_name()) ? "NO: it has no name" : "YES: it does have a name");
               if (!symbolTable->get_no_name())
                    printf ("SymbolTable name = %s \n",symbolTable->get_name().str());
                 else
                    ROSE_ASSERT (symbolTable->get_name().str() == NULL);
#endif

               if (symbolTable->get_table() != NULL)
                  {
                    SgSymbolTable::hash_iterator i = symbolTable->get_table()->begin();
                    int counter = 0;
                    while (i != symbolTable->get_table()->end())
                       {
                         ROSE_ASSERT ( isSgSymbol( (*i).second ) != NULL );

                      // printf ("Initial info: number: %d pair.first (SgName) = %s pair.second (SgSymbol) sage_class_name() = %s \n",
                      //      counter,(*i).first.str(),(*i).second->sage_class_name());

                         SgSymbol* symbol = isSgSymbol((*i).second);
                         ROSE_ASSERT ( symbol != NULL );
                         SgType* type = symbol->get_type();
                         ROSE_ASSERT ( type != NULL );

                         SgNamedType* namedType = isSgNamedType(type);
                         string typeName;
                         if (namedType != NULL)
                            {
                              SgName n = namedType->get_name();
                              typeName = namedType->get_name().str();
                           // char* nameString = namedType->get_name().str();
                           // printf ("Type is: (named type) = %s \n",nameString);
                              ROSE_ASSERT (identifingTypeName.c_str() != NULL);
                           // ROSE_ASSERT (typeName != NULL);
                           // printf ("In getTransformationOptions(): typeName = %s identifingTypeName = %s \n",typeName.c_str(),identifingTypeName.c_str());
                           // if ( (typeName != NULL) && ( typeName == identifingTypeName) )
                              if ( typeName == identifingTypeName )
                                 {
                                // Now look at the parameter list to the constructor and save the
                                // values into the list.

                                // printf ("Now save the constructor arguments! \n");

                                   SgVariableSymbol* variableSymbol = isSgVariableSymbol(symbol);

                                   if ( variableSymbol != NULL )
                                      {
                                        SgInitializedName* initializedNameDeclaration = variableSymbol->get_declaration();
                                        ROSE_ASSERT (initializedNameDeclaration != NULL);

                                        SgDeclarationStatement* declarationStatement = initializedNameDeclaration->get_declaration();
                                        ROSE_ASSERT (declarationStatement != NULL);

                                        SgVariableDeclaration* variableDeclaration = isSgVariableDeclaration(declarationStatement);
                                        ROSE_ASSERT (variableDeclaration != NULL);

                                        getTransformationOptionsFromVariableDeclarationConstructorArguments(variableDeclaration,generatedList);

                                        foundTransformationOptimizationSpecifier = true;

                                     // printf ("Exiting after saving the constructor arguments! \n");
                                     // ROSE_ABORT();
                                      }
                                     else
                                      {
#if 0
                                        printf ("Not a SgVariableSymbol: symbol->sage_class_name() = %s \n",
                                             symbol->sage_class_name());
#endif
                                      }
                                 }
                                else
                                 {
#if 0
                                   printf ("typeName != identifingTypeName : symbol->sage_class_name() = %s \n",
                                        symbol->sage_class_name());
#endif
#if 0
                                // I don't think this should ever be NULL (but it is sometimes)
                                   if (typeName != NULL)
                                        printf ("typeName == NULL \n");
#endif
                                 }
                            }
                           else
                            {
                              typeName = (char *)type->sage_class_name();
                            }

                      // printf ("In while loop at the base: counter = %d \n",counter);
                         i++;
                         counter++;
                       }
                  }
                 else
                  {
                 // printf ("Pointer to symbol table is NULL \n");
                  }

            // printf ("foundTransformationOptimizationSpecifier = %s \n",foundTransformationOptimizationSpecifier ? "true" : "false");

            // SgSymbolTable objects don't have a parent node (specifically they lack a get_parent
            // member function in the interface)!
               break;
             }

          case BASIC_BLOCK_STMT:
             {
            // List the variable in each scope
            // printf ("List all the variables in this scope! \n");
               SgBasicBlock* basicBlock = isSgBasicBlock(astNode);
               ROSE_ASSERT (basicBlock != NULL);

               SgSymbolTable* symbolTable = basicBlock->get_symbol_table();
               ROSE_ASSERT (symbolTable != NULL);
               getTransformationOptions ( symbolTable, generatedList, identifingTypeName );

            // Next go (fall through this case) to the default case so that we traverse the parent
            // of the SgBasicBlock.
            // break;
             }

          default:
            // Most cases will be the default (this is by design)
            // printf ("default in switch found in globalQueryGetListOperandStringFunction() (sage_class_name = %s) \n",astNode->sage_class_name());

            // Need to recursively backtrack through the parents until we reach the SgGlobal (global scope)
               SgStatement* statement = isSgStatement(astNode);
               if (statement != NULL)
                  {
                    SgNode* parentNode = statement->get_parent();
                    ROSE_ASSERT (parentNode != NULL);
//                  printf ("parent = %p parentNode->sage_class_name() = %s \n",parentNode,parentNode->sage_class_name());
                    SgStatement* parentStatement = isSgStatement(parentNode);
                    if (parentStatement == NULL)
                       {
                         printf ("parentStatement == NULL: statement (%p) is a %s \n",statement,statement->sage_class_name());
                         printf ("parentStatement == NULL: statement->get_file_info()->get_filename() = %s \n",statement->get_file_info()->get_filename());
                         printf ("parentStatement == NULL: statement->get_file_info()->get_line() = %d \n",statement->get_file_info()->get_line());
                       }
                    ROSE_ASSERT (parentStatement != NULL);

                 // Call this function recursively (directly rather than through the query mechanism)
                    getTransformationOptions ( parentStatement, generatedList, identifingTypeName );
                  }
                 else
                  {
                 // printf ("astNode is not a SgStatement! \n");
                  }

               break;
        }

#if 0
     printf ("At BASE of getTransformationOptions(): astNode->sage_class_name() = %s size of generatedList = %d \n",
          astNode->sage_class_name(),generatedList.size());
#endif

  // printf ("######################### END OF TRANSFORMATION OPTION QUERY ######################## \n");
   }
示例#25
0
static std::string
sourcePositionInformation (SgNode* node)
   {
  // DQ (8/31/2013): Adding source position information for DOT output.
     string ss;

     SgLocatedNode* locatedNode = isSgLocatedNode(node);
     if (locatedNode != NULL)
        {
          Sg_File_Info* fileInfo = locatedNode->get_file_info();
          if (fileInfo != NULL)
             {
               bool hasSpecialMode = false;
               if (fileInfo->isCompilerGenerated() == true)
                  {
                    ss += "compiler generated\\n";
                    hasSpecialMode = true;
                  }
                 else
                  {
                    if (fileInfo->isFrontendSpecific() == true)
                       {
                         ss += "front-end specific\\n";
                         hasSpecialMode = true;
                       }
                      else
                       {
                         if (fileInfo->isTransformation() == true)
                            {
                              ss += "is part of transformation\\n";
                              hasSpecialMode = true;
                            }
                           else
                            {
                           // ss += "???\\n";
                            }
                       }
                  }

               if (hasSpecialMode == true)
                  {
                    if (fileInfo->isOutputInCodeGeneration() == true)
                       {
                         ss += "IS output in generated code\\n";
                       }
                      else
                       {
                         ss += "is NOT output in generated code\\n";
                       }
                  }
                 else
                  {
                 // DQ (9/1/2013): Name a few cases were we want to output the end of the IR node construct's source position range.
                 // bool outputEndOfConstruct = (isSgAggregateInitializer(node) != NULL || isSgScopeStatement(node) != NULL);
                    bool outputEndOfConstruct = true; // (isSgAggregateInitializer(node) != NULL || isSgStatement(node) != NULL);

                    if (outputEndOfConstruct == true)
                       {
                      // Output the end of the range represented by the IR node's source position.
                         ss += generateFileLineColumnString(locatedNode->get_startOfConstruct());
                         ss += generateFileLineColumnString(locatedNode->get_endOfConstruct());
                       }
                      else
                       {
                      // For an SgStatement this is the startOfConstruct, but for an SgExpression this is the operator position (or sometimes equal to the startOfConstruct).
                         ss += generateFileLineColumnString(fileInfo);
                       }
                  }
             }
            else
             {
               ss += "no source position available\\n";
             }
        }
       else
        {
       // DQ (9/1/2013): We could handle the source position of some other IR nodes (e.g. output name of the file for SgFile).
          SgFile* file = isSgFile(node);
          if (file != NULL)
             {
               ROSE_ASSERT(file->get_file_info() != NULL);
               ss += generateFileLineColumnString(file->get_file_info());
             }
        }

     return ss;
   }
示例#26
0
AttachPreprocessingInfoTreeTraversalInheritedAttrribute
AttachAllPreprocessingInfoTreeTrav::evaluateInheritedAttribute ( SgNode *n, AttachPreprocessingInfoTreeTraversalInheritedAttrribute inh)
   {
     wrap_data_used_by_AttachPreprocessingInfoTreeTrav_t save_data;

     SgFile *currentFilePtr =  dynamic_cast<SgFile*>(n);
     SgLocatedNode *currentLocNodePtr = dynamic_cast<SgLocatedNode*>(n);
     int file_name_id = -1;
     Sg_File_Info * file_info_ptr = NULL;
     bool isCompilerGenerated = false;
     bool isTransformation = false;

     if ( ( currentFilePtr == NULL ) && ( currentLocNodePtr == NULL ) )
          return inh;

  // get a valid file name, and check if it is a new file; if yes, get
  // all the comments and store the list into map. Then set save_data
  // to prepare for the parent function.

  // DQ (12/1/2008): I think this code can be simplified now, but I am not clear how it should be done!

  // 1. find the file name for the current node:
     if ( currentFilePtr!=NULL )
        {
          file_name_id = currentFilePtr->get_file_info()->get_file_id();
        }
       else
        {
          if ( currentLocNodePtr!=NULL )
             {
               file_info_ptr = currentLocNodePtr->get_file_info();
               assert ( file_info_ptr!=NULL );

            // Pi: compiler generated nodes have no real file names with them,
            // so use the currentFileName as their names:
               isCompilerGenerated = file_info_ptr->isCompilerGenerated();
            // isCompilerGenerated = file_info_ptr->isCompilerGeneratedNodeToBeUnparsed();
               isTransformation = file_info_ptr->isTransformation();
               if ( isCompilerGenerated == true || isTransformation == true )
                  {
                    file_name_id = currentFileNameId;
                  }
                 else
                  {
                    file_name_id = file_info_ptr->get_file_id();
                  }
             }
        }

  // 2. check whether the file name is new:
  // AS(09/21/07) Reset start_index since we are dealing with a new file
     start_index = 0;

     map<int, wrap_data_used_by_AttachPreprocessingInfoTreeTrav_t>::iterator attr_list_itr = map_of_all_attributes.find(file_name_id);

  // If the name is not in the map then ... it is a new file and we have to process it
     if ( attr_list_itr == map_of_all_attributes.end() )
        {
#ifdef outputallfilenamefound
          cerr << "-->>> NEW file : " << file_name_str << endl;
#endif
          save_data.previousLocNodePtr = previousLocNodePtr;

       // AS(092907) Only collect the filenames we are interested in
       // AS(093007) Logic to include or exclude finding comments in paths
          bool includePath = true;

          std::string file_name_str = Sg_File_Info::getFilenameFromID(file_name_id);

       // If the command line directive to look for include paths has been
       // specified. See if the current filename is in the list of
       // included paths.
          if( lookForIncludePaths == true )
             {
               includePath = false;
               for (std::vector<std::string>::iterator iItr = pathsToInclude.begin(); iItr != pathsToInclude.end(); ++iItr)
                  {
                    if ( file_name_str.find(*iItr) != string::npos )
                       {
                         includePath  = true; 
                         break;                 
                       }
                  }
             }

          bool excludePath = false;

       // If the command line directive to look for exclude paths has been
       // specified. See if the current filename is in the list of
       // excluded paths.
          if ( lookForExcludePaths == true )
             {
               for (std::vector<std::string>::iterator iItr = pathsToExclude.begin(); iItr != pathsToExclude.end(); ++iItr)
                  {
                    if ( file_name_str.find(*iItr) != string::npos )
                       {
                         excludePath  = true; 
                         break;
                       }
                  }
             }

          ROSE_ASSERT(inh.currentListOfAttributes != NULL);

          if ( (excludePath == false) && (includePath == true) )
             {
            // This scans the file and collects the token stream...
               printf ("AttachAllPreprocessingInfoTreeTrav::evaluateInheritedAttribute(): Calling getPreprocessorDirectives for file = %s \n",file_name_str.c_str());

            // DQ (11/30/2008): Moved currentListOfAttributes to inherited attribute
            // save_data.currentListOfAttributes = getPreprocessorDirectives(file_name_str);
            // save_data.currentListOfAttributes = inh.currentListOfAttributes;

            // This will work for C/C++ but not for Fortran.
            // For Fortran use: returnListOfAttributes->collectPreprocessorDirectivesAndCommentsForAST(fileNameForDirectivesAndComments,ROSEAttributesList::e_Fortran9x_language);
            // or: returnListOfAttributes->collectPreprocessorDirectivesAndCommentsForAST(fileNameForDirectivesAndComments,ROSEAttributesList::e_Fortran77_language);
               save_data.currentListOfAttributes = getPreprocessorDirectives(file_name_str);
             }
            else
             {
            // This builds an empty list; does not traverse the file
               printf ("AttachAllPreprocessingInfoTreeTrav::evaluateInheritedAttribute(): Building an empty list to represent the data from file = %s \n",file_name_str.c_str());

            // DQ (11/30/2008): Moved currentListOfAttributes to inherited attribute
            // save_data.currentListOfAttributes = new ROSEAttributesList();
            // save_data.currentListOfAttributes = inh.currentListOfAttributes;
               save_data.currentListOfAttributes = new ROSEAttributesList();
             }

       // DQ (11/30/2008): Moved currentListOfAttributes to inherited attribute
       // save_data.sizeOfCurrentListOfAttributes = save_data.currentListOfAttributes->getLength();
          map_of_all_attributes[file_name_id] = save_data;

        }
       else
        {
          save_data = (*attr_list_itr).second;
        }

  // 3. set data used by the parent before calling it:
     currentFileNameId             = file_name_id;
     previousLocNodePtr            = save_data.previousLocNodePtr;

  // DQ (11/30/2008): Moved currentListOfAttributes to inherited attribute
  // currentListOfAttributes       = save_data.currentListOfAttributes;
  // sizeOfCurrentListOfAttributes = save_data.sizeOfCurrentListOfAttributes;

  // 4. call the parent and record changes to the data used:
     AttachPreprocessingInfoTreeTraversalInheritedAttrribute inh_rsl = AttachPreprocessingInfoTreeTrav::evaluateInheritedAttribute(n, inh);
     save_data.previousLocNodePtr = previousLocNodePtr;

  // DQ (11/30/2008): Moved currentListOfAttributes to inherited attribute
  // save_data.currentListOfAttributes = currentListOfAttributes;
  // save_data.sizeOfCurrentListOfAttributes = sizeOfCurrentListOfAttributes;
     map_of_all_attributes[currentFileNameId] = save_data;

  // 5. set the first attachable node for each file to make it simple
  // 5. to attach rest preproc info (the special case when a file
  // 5. contains no IR nodes): such info is attached to the first node
  // 5. of the next file.
     if ( dynamic_cast<SgStatement*>(n) != NULL )
        {
       // Nodes that should not have comments attached (since they are not unparsed)
       // Conditions obtained from src/ROSETTA/Grammar/LocatedNode.code:251
          switch ( n->variantT() )
             {
               case V_SgForInitStatement:
               case V_SgTypedefSeq:
               case V_SgCatchStatementSeq:
               case V_SgFunctionParameterList:
               case V_SgCtorInitializerList:
                    goto return_inh;

               default:
                  {
                 // 5. if the first node for a file doesn't exist, then add it; otherwise do nothing:
                    map<int, int>::iterator first_node_itr = map_of_file_order.find(currentFileNameId);
                    if ( first_node_itr == map_of_file_order.end() )
                       {
                         map_of_file_order[currentFileNameId] = nFiles;
                         add_first_node_for_file(currentFileNameId, n, nFiles);
                         nFiles++;
                       }
                    break;
                  }
             }
        }

  // The inh/inh_rsl is no use for now.
     return_inh:

     return inh_rsl;
   }
示例#27
0
AttachPreprocessingInfoTreeTraversalSynthesizedAttribute
AttachAllPreprocessingInfoTreeTrav::evaluateSynthesizedAttribute ( SgNode *n, AttachPreprocessingInfoTreeTraversalInheritedAttrribute inh, SubTreeSynthesizedAttributes st)
   {
     wrap_data_used_by_AttachPreprocessingInfoTreeTrav_t save_data;

     SgFile *currentFilePtr =  dynamic_cast<SgFile*>(n);
     SgLocatedNode *currentLocNodePtr = dynamic_cast<SgLocatedNode*>(n);
     int file_name_id = -1;
     Sg_File_Info * file_info_ptr = NULL;
     bool isCompilerGenerated = false;
     bool isTransformation = false;

     if( ( currentFilePtr != NULL ) || ( currentLocNodePtr != NULL ) )
        {
       // get a valid file name, and check if it is a new file; if yes, get
       // all the comments and store the list into map. Then set save_data
       // to prepare for the parent function.

       // 1. find the file name for the current node:
          if ( currentFilePtr!=NULL )
             {
               file_name_id = currentFilePtr->get_file_info()->get_file_id();
             }
            else
             {
               if ( currentLocNodePtr!=NULL )
                  {
                    file_info_ptr = currentLocNodePtr->get_file_info();
                    assert ( file_info_ptr!=NULL );

                 // Pi: compiler generated nodes have no real file names with them,
                 // so use the currentFileName as their names:
                    isCompilerGenerated = file_info_ptr->isCompilerGenerated();
                 // isCompilerGenerated = file_info_ptr->isCompilerGeneratedNodeToBeUnparsed();
                    isTransformation = file_info_ptr->isTransformation();
                    if ( isCompilerGenerated==true || isTransformation==true )
                       {
                         file_name_id = currentFileNameId;
                       }
                      else
                       {
                         file_name_id = file_info_ptr->get_file_id();
                       }
                  }
             }

       // 2. check whether the file name is new:
       // AS(09/21/07) Reset start_index since we are dealing with a new file
          start_index = 0;

          map<int, wrap_data_used_by_AttachPreprocessingInfoTreeTrav_t>::iterator attr_list_itr = map_of_all_attributes.find(file_name_id);
          if ( attr_list_itr==map_of_all_attributes.end() )
             {
#ifdef outputallfilenamefound
               cerr << "-->>> NEW file : " << file_name_str << endl;
#endif
               save_data.previousLocNodePtr = previousLocNodePtr;

            // AS(093007) Logic to include or exclude finding comments in paths
               bool includePath = true;
               std::string file_name_str = Sg_File_Info::getFilenameFromID(file_name_id);

            // If the command line directive to look for include paths has been
            // specified. See if the current filename is in the list of
            // included paths.
               if( lookForIncludePaths == true )
                  {
                    includePath = false;
                    for(std::vector<std::string>::iterator iItr = pathsToInclude.begin(); iItr != pathsToInclude.end(); ++iItr)
                       {
                         if( file_name_str.find(*iItr) != string::npos )
                            {
                              includePath  = true; 
                              break;
                            }
                       }
                  }

               bool excludePath = false;

            // If the command line directive to look for exclude paths has been
            // specified. See if the current filename is in the list of
            // excluded paths.
               if( lookForExcludePaths == true )
                  {
                    for(std::vector<std::string>::iterator iItr = pathsToExclude.begin(); iItr != pathsToExclude.end(); ++iItr)
                       {
                         if( file_name_str.find(*iItr) != string::npos )
                            {
                              excludePath  = true; 
                              break;
                            }
                       }
                  }

#if 0
            // DQ (11/30/2008): Moved currentListOfAttributes to inherited attribute
               if( (excludePath == false) && (includePath == true) )
                    save_data.currentListOfAttributes = getPreprocessorDirectives(file_name_str);
                 else
                    save_data.currentListOfAttributes = new ROSEAttributesList;

               save_data.sizeOfCurrentListOfAttributes = save_data.currentListOfAttributes->getLength();
#endif
               map_of_all_attributes[file_name_id] = save_data;
             }
            else
             {
               save_data = (*attr_list_itr).second;
             }

       // 3. set data used by the parent before calling it:
          currentFileNameId = file_name_id;
          previousLocNodePtr = save_data.previousLocNodePtr;
#if 0
       // DQ (11/30/2008): Moved currentListOfAttributes to inherited attribute
          currentListOfAttributes = save_data.currentListOfAttributes;
          sizeOfCurrentListOfAttributes = save_data.sizeOfCurrentListOfAttributes;
#endif
        }

     AttachPreprocessingInfoTreeTraversalSynthesizedAttribute syn;

     if( ( currentFilePtr != NULL ) || ( currentLocNodePtr != NULL ) )
        {
          syn = AttachPreprocessingInfoTreeTrav::evaluateSynthesizedAttribute(n, inh, st);
          save_data.previousLocNodePtr = previousLocNodePtr;

#if 0
       // DQ (11/30/2008): Moved currentListOfAttributes to inherited attribute
          save_data.currentListOfAttributes = currentListOfAttributes;
          save_data.sizeOfCurrentListOfAttributes = sizeOfCurrentListOfAttributes;
#endif

          map_of_all_attributes[currentFileNameId] = save_data;
        }
 
  // The inh/st/syn is no use for now.
  // return_syn:
     return syn;
   }
示例#28
0
文件: waveHelpers.C 项目: 8l/rose
	bool
checkIfNodeMaps(token_type tok, SgNode* node)
{
	bool nodeMaps = false;

	using namespace boost::wave;

        //By definition a compiler generated node can
        //not map to the token stream
        SgLocatedNode* compilerGeneratedNode = isSgLocatedNode(node);
        if( compilerGeneratedNode != NULL  )
          if(compilerGeneratedNode->get_file_info()->isCompilerGenerated() == true)
            return false;

//	     std::cout << get_token_name(tok) << " " << std::string(tok.get_value().c_str()) << " " << node->class_name() << " " << node->get_file_info()->get_line() << std::endl;
	//Mapping literal token id's
	switch(token_id(tok)){
		case T_PP_NUMBER:{

					 if(isSgValueExp(node)!=NULL)
						 nodeMaps=true;
					 break;
				 }
		case T_CHARLIT:{
				       if( ( isSgCharVal(node) != NULL ) |
						       ( isSgUnsignedCharVal(node) != NULL )
					 )
					       nodeMaps = true;
				       break;
			       }
		case T_FLOATLIT:{
					if( isSgFloatVal(node) != NULL )
						nodeMaps = true;

					break;
				}
		case T_INTLIT:{
				      if( ( isSgIntVal(node) != NULL ) || 
						      ( isSgUnsignedIntVal(node) != NULL ) 	       
					)
					      nodeMaps = true;
				      break;
			      }
		case T_LONGINTLIT:
			      {
				      if( ( isSgLongIntVal(node) != NULL ) |
						      ( isSgLongLongIntVal(node) != NULL ) |
						      ( isSgUnsignedLongLongIntVal(node) != NULL )

					)
					      nodeMaps = true;
				      break;
			      }
		case T_STRINGLIT:
			      {
				      if( isSgStringVal(node) != NULL )
					      nodeMaps = true;
				      break;
			      }
                case T_QUESTION_MARK:
                              {
                   		      if( isSgConditionalExp(node) != NULL )
                                        nodeMaps = true;
                                      break;
                              }
		case T_FALSE:
		case T_TRUE:
			      if( isSgBoolValExp(node) != NULL  )
				      nodeMaps = true;
			      break;
		default:
			      break;
	}

	//map keyword token id's
	switch(token_id(tok)){

		case T_ASM:
			if( isSgAsmStmt(node) != NULL  )
				nodeMaps = true;
			break;

		case T_AUTO: //auto
			//dont know
			break;
			/*case T_BOOL:
			//dont think this can be mapped
			break;*/
		case T_BREAK:
			if( isSgBreakStmt(node) != NULL  )
				nodeMaps = true;
			break;

		case T_CASE:
			if( isSgCaseOptionStmt(node) != NULL  )
				nodeMaps = true;
			break;

		case T_CATCH:
			if( isSgCatchOptionStmt(node) != NULL )
				nodeMaps = true;
			break;
			/*
			   case T_CHAR:
			//dont know
			break;
			*/	    

		case boost::wave::T_CLASS:
			if( isSgClassDeclaration(node) != NULL )
				nodeMaps = true;
			break;

		case T_CONST:
			// is it SgConstVolatileModifier?
			//dont know
			break;
		case T_CONTINUE:
			if( isSgContinueStmt(node) != NULL )
				nodeMaps = true;
			break;

			//case T_DEFAULT:
			//Dont know
			//  break;


		case T_DELETE:
			if( isSgDeleteExp(node) != NULL  )
				nodeMaps = true;
			break;

		case T_DO:
			if( isSgDoWhileStmt(node) != NULL  )
				nodeMaps = true;
			break;

		case T_ELSE:
			//dont know
			break;

		case T_EXPLICIT:
			//dont know
			break;
		case T_EXPORT:
		case T_EXTERN:
			break;
		case T_FOR:

			if( isSgForStatement(node) != NULL  )
				nodeMaps = true;
			break;
		case T_FRIEND:
			//dont know
			break;
		case T_GOTO:

			if( isSgGotoStatement(node) != NULL  )
				nodeMaps = true;
			break;

		case T_IF:
			//dont know how to handle this because if if-else
			break;
		case T_INLINE:
			//dont know
			break;
		case T_MUTABLE:
			//dont know
			break;
		case T_NAMESPACE:

			if( ( isSgNamespaceAliasDeclarationStatement(node) != NULL  ) |
					(isSgNamespaceDeclarationStatement(node) != NULL )
			  )
				nodeMaps = true;
			break;
		case T_NEW:

			if( isSgNewExp(node) != NULL  )
				nodeMaps = true;
			break;
		case T_OPERATOR:
		case T_PRIVATE:
		case T_PROTECTED:
		case T_PUBLIC:
		case T_REGISTER:
		case T_REINTERPRETCAST:
			//dont know
			break;

		case T_RETURN:
			if( isSgReturnStmt(node) != NULL  )
				nodeMaps = true;
			break;

		case T_SIZEOF:
			if( isSgSizeOfOp(node) != NULL  )
				nodeMaps = true;
			break;
		case T_STATIC:
		case T_STATICCAST:
			//dont know
			break;
		case T_STRUCT:
			if( isSgClassDeclaration(node) != NULL  )
				nodeMaps = true;
			break;
		case T_SWITCH:
			if( isSgSwitchStatement(node) != NULL  )
				nodeMaps = true;
			break;
			//case T_TEMPLATE:
			//dont know
			//   break;
		case T_THIS:

			if( isSgThisExp(node) != NULL  )
				nodeMaps = true;

			break;
		case T_THROW:

			if( isSgThrowOp(node) != NULL  )
				nodeMaps = true;

			break;
		case T_TRY:

			if( isSgTryStmt(node) != NULL  )
				nodeMaps = true;

			break;
		case boost::wave::T_TYPEDEF:

			if( isSgTypedefDeclaration(node) != NULL  )
				nodeMaps = true;

			break;

		case T_TYPEID:
			if( isSgTypeIdOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_TYPENAME:
			//dont know
			break;
		case T_UNION:
			if( isSgClassDeclaration(node) != NULL  )
				nodeMaps = true;

			break;
		case T_USING:
			if( isSgUsingDeclarationStatement(node) != NULL  )
				nodeMaps = true;

			break;
		case T_VIRTUAL:
			//dont know
			break;
		case T_VOLATILE:

			//is it SgConstVolatileModifier ?
			break;

		case T_WHILE:
			if( isSgWhileStmt(node) != NULL  )
				nodeMaps = true;

			break;

		default:
			break;

	}


	//map operator token id's
	switch(token_id(tok)){
		case T_AND:
          	case T_ANDAND:
			if( isSgAndOp(node) != NULL | isSgBitAndOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_ASSIGN:
			if ( isSgAssignOp(node) != NULL | isSgAssignInitializer(node) != NULL )
				nodeMaps = true;
			break;
		case T_ANDASSIGN:
			//do not know
			break;
		case T_OR:
			if ( isSgBitOrOp(node) != NULL || isSgOrOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_ORASSIGN:
			//do not know
			break;
		case T_XOR:
			if ( isSgBitXorOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_XORASSIGN:
			if ( isSgXorAssignOp(node) != NULL )
				nodeMaps = true;
			break;	
		case T_COMMA:
			if ( isSgCommaOpExp(node) != NULL )
				nodeMaps = true;
			break;
		case T_COLON:
			//dont know
			break;

		case T_DIVIDE:
			if ( isSgDivideOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_DIVIDEASSIGN:
			if ( isSgDivAssignOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_DOT:
			if ( isSgDotExp(node) != NULL )
				nodeMaps = true;
			break;


		case T_DOTSTAR:
			if ( isSgDotExp(node) != NULL )
				nodeMaps = true;
			break;


		case T_ELLIPSIS:
			//Dont know
			break;
		case T_EQUAL:
			if ( isSgEqualityOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_GREATER:
			if ( isSgGreaterThanOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_GREATEREQUAL:
			if ( isSgGreaterOrEqualOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_LEFTBRACE:
			//Dont know
			break;
		case T_LESS:
			if ( isSgLessThanOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_LESSEQUAL:
			if ( isSgLessOrEqualOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_LEFTPAREN:
			//Dont know
			break;

		case T_LEFTBRACKET:
		case T_RIGHTBRACKET:
			if ( isSgPntrArrRefExp(node) != NULL ) 
                             nodeMaps = true;
			break;
		case T_MINUS:
			if ( ( isSgSubtractOp(node) != NULL ) |
					( isSgMinusOp(node) != NULL ) )
				nodeMaps = true;
			break;

		case T_MINUSASSIGN:
			if ( isSgMinusAssignOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_MINUSMINUS:
			if ( isSgMinusMinusOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_PERCENT:
			if ( isSgModOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_PERCENTASSIGN:
			if ( isSgModAssignOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_NOT:
			if ( isSgNotOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_NOTEQUAL:
			if ( isSgNotEqualOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_OROR:
			if ( isSgOrOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_PLUS:
			if ( isSgAddOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_PLUSASSIGN:
			if ( isSgPlusAssignOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_PLUSPLUS:
			if ( isSgPlusPlusOp(node) != NULL )
				nodeMaps = true;
			break;


		case T_ARROW:
			if ( isSgArrowExp(node) != NULL )
				nodeMaps = true;
			break;

		case T_ARROWSTAR:
			if ( isSgArrowStarOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_QUESTION_MARK:
			//dont know
			break;

		case T_RIGHTBRACE:
		case T_RIGHTPAREN:
		case T_COLON_COLON:
		case T_SEMICOLON:
			//dont know
			break;
		case T_SHIFTLEFT:
			if ( isSgLshiftOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_SHIFTLEFTASSIGN:
			if ( isSgLshiftAssignOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_SHIFTRIGHT:
			if ( isSgRshiftOp(node) != NULL )
				nodeMaps = true;
			break;
		case T_SHIFTRIGHTASSIGN:
			if ( isSgRshiftAssignOp(node) != NULL )
				nodeMaps = true;
			break;

		case T_STAR:
			//dont know
                        if ( isSgMultiplyOp(node) != NULL || isSgPointerType(node) )
                          nodeMaps = true;
			break;
		case T_COMPL://~

                        if( isSgBitComplementOp(node)  != NULL  )
                          nodeMaps = true;
			//Dont know
			break;
		case T_STARASSIGN:
			if ( isSgMultAssignOp(node) != NULL )
				nodeMaps = true;

			break;
		case T_POUND_POUND:
		case T_POUND:
			//dont know
			break;

		case T_AND_ALT:
		case T_ANDASSIGN_ALT:
		case T_OR_ALT:
		case T_ORASSIGN_ALT:
		case T_XOR_ALT:
		case T_XORASSIGN_ALT:
		case T_LEFTBRACE_ALT:
		case T_LEFTBRACKET_ALT:
		case T_NOT_ALT:
		case T_NOTEQUAL_ALT:
		case T_RIGHTBRACE_ALT:
		case T_RIGHTBRACKET_ALT:
		case T_COMPL_ALT:
		case T_POUND_POUND_ALT:
		case T_POUND_ALT:
		case T_OR_TRIGRAPH:
		case T_XOR_TRIGRAPH:
		case T_LEFTBRACE_TRIGRAPH:
		case T_LEFTBRACKET_TRIGRAPH:
		case T_RIGHTBRACE_TRIGRAPH:
		case T_RIGHTBRACKET_TRIGRAPH:
		case T_COMPL_TRIGRAPH:
		case T_POUND_POUND_TRIGRAPH:
		case T_POUND_TRIGRAPH:
			//dont know
			break;
		default:
			break;
	}

	switch(token_id(tok)){
		case T_FALSE:
		case T_TRUE:
			break;
		case T_CHARLIT:
			if(SgProject::get_verbose() >= 1)
				std::cout << "char " << std::string(tok.get_value().c_str()) << std::endl;

			if( isSgCharVal(node) != NULL ){
				SgCharVal* charVal = isSgCharVal(node);
				if(SgProject::get_verbose() >= 1)
					std::cout << std::string(tok.get_value().c_str()) << std::endl;
				char tmp = charVal->get_value();
				if(SgProject::get_verbose() >= 1)
					std::cout << "From charlit: " << tmp << std::endl;

				if(("\""+std::string(&tmp)+"\"") == std::string(tok.get_value().c_str()) )
					nodeMaps = true;


			}
			break;
		case T_STRINGLIT:
			{
				if(SgProject::get_verbose() >= 1)
					std::cout << "string " <<std::string(tok.get_value().c_str()) << std::endl;

				if( isSgStringVal(node) != NULL ){
					SgStringVal* stringVal = isSgStringVal(node);
					if(SgProject::get_verbose() >= 1){
						std::cout << std::string(tok.get_value().c_str()) << std::endl;
						std::cout << "stringlit: " << stringVal->get_value() << std::endl;
					}
					if(("\""+stringVal->get_value()+"\"") == std::string(tok.get_value().c_str()) )
						nodeMaps = true;


				}
				break;
			}
			/*case V_SgWcharVal:

			  if( isSgWcharVal(node) != NULL )
			  if( std::string(isSgWcharVal(node)->get_value()) == std::string(tok.get_value().c_str()) )
			  nodeMaps = true;

			  break;*/
		default:
			break; 

	}

	if( token_id(tok) == T_IDENTIFIER ){
		if( isSgInitializedName(node) != NULL ){

			std::cout << "Identifier" << std::endl;
			SgInitializedName* initName = isSgInitializedName(node);
			std::cout <<  initName->get_name().getString() << " " << std::string(tok.get_value().c_str()) << std::endl;
			if( initName->get_name().getString() == std::string(tok.get_value().c_str()) ){
				nodeMaps = true;
			}
		}else if( isSgVarRefExp(node) != NULL ){
			SgVariableSymbol* varSymbol = isSgVarRefExp(node)->get_symbol();
			SgInitializedName* initName = varSymbol->get_declaration();
			if( initName->get_name().getString() == std::string(tok.get_value().c_str()) ){
				nodeMaps = true;
                                std::cout << "Maps:" << initName->get_name().getString() << " " << std::string(tok.get_value().c_str()) 
                                          << std::endl; 
                        }else
                          std::cout << "DONT Map:" << initName->get_name().getString() << " " << std::string(tok.get_value().c_str()) 
                                          << std::endl; 

		}else if( isSgFunctionRefExp(node) != NULL){
			SgFunctionRefExp* funcRef = isSgFunctionRefExp(node);
			SgFunctionSymbol* funcSymbol = funcRef->get_symbol_i();
			if( funcSymbol->get_declaration()->get_name().getString() == std::string(tok.get_value().c_str()) )
				nodeMaps = true;

		}else if( isSgMemberFunctionRefExp(node) != NULL){
			SgMemberFunctionRefExp* funcRef = isSgMemberFunctionRefExp(node);
			SgMemberFunctionSymbol* funcSymbol = funcRef->get_symbol();
			if( funcSymbol->get_declaration()->get_name().getString() == std::string(tok.get_value().c_str()) )
				nodeMaps = true;

		}

	}

        //Exceptions to the general rule

		switch(token_id(tok)){
                  case T_CHARLIT:
                    {
                      switch(node->variantT())
                      {
                        case V_SgCharVal:
                        case V_SgComplexVal:
                        case V_SgDoubleVal:
                        case V_SgEnumVal:
                        case V_SgFloatVal:
                        case V_SgIntVal:
                        case V_SgLongDoubleVal:
                        case V_SgLongIntVal:
                        case V_SgLongLongIntVal:
                        case V_SgShortVal:
                        case V_SgStringVal:
                        case V_SgUnsignedCharVal:
                        case V_SgUnsignedIntVal:
                        case V_SgUnsignedLongLongIntVal:
                        case V_SgUnsignedLongVal:
                        case V_SgUnsignedShortVal:
                        case V_SgWcharVal: 
                          {
                            nodeMaps=true;
                            break;
                          }
                        default:
                          break;

                      };

                      break;
                    };
                }
	switch(boost::wave::token_id(tok)){
		case boost::wave::T_CHAR:
                  {
                  if(isSgTypeChar(node) != NULL)
                    nodeMaps=true;
                  break;
                  }
		case boost::wave::T_CONST:
                  break;
		case boost::wave::T_DOUBLE: 		
                  if(isSgTypeDouble(node) != NULL)
                    nodeMaps=true;
                  break;

		case boost::wave::T_INT:
                  if(isSgTypeInt(node) != NULL)
                    nodeMaps=true;
                  break;

		case boost::wave::T_LONG:
                  if(isSgTypeLong(node) != NULL)
                    nodeMaps=true;
                  break;

		case boost::wave::T_SHORT:
                 if(isSgTypeShort(node) != NULL)
                    nodeMaps=true;
                  break;

		case boost::wave::T_SIGNED:
		case boost::wave::T_UNSIGNED:
		case boost::wave::T_VOID:
                  if(isSgTypeVoid(node) != NULL)
                    nodeMaps=true;
                  break;
		default:
			break;

	};

	return nodeMaps;
}
示例#29
0
Rose_STL_Container<
  ControlStructureContainer *
  >queryFindCommentsInScope (const string stringPrefixToMatch,
			     const string stringToMatch,
			     SgScopeStatement * sageScopeStatement)
{
  ROSE_ASSERT (stringPrefixToMatch.length () > 0);
  ROSE_ASSERT (stringToMatch.length () > 0);
  ROSE_ASSERT (sageScopeStatement != NULL);

  Rose_STL_Container< ControlStructureContainer * >returnList;

  //find all pragmas who match the stringToMatch
   //cout << "Before pragma search" << endl;
   /*list < SgNode * >pragmaStatements =
    NodeQuery::querySubTree (sageScopeStatement,
			     new SgName (stringToMatch.c_str ()),
			     NodeQuery::PragmaDeclarationFromName);
   */
    //list<SGNode*> pragmaStatements ; 
    //cout << "After pragma search" << endl;

/*  cout << "BEFORE LIST" << endl; 
  list < SgNode * >pragmaStatements = queryNodePragmaStatementFromName2(sageScopeStatement,
		                            new SgName(stringToMatch.c_str()));
  cout << "AFTER LIST" << endl;*/
  //return the pragmas in containers
/*  for (list < SgNode * >::iterator i = pragmaStatements.begin ();
       i != pragmaStatements.end (); ++i)
    {
      SgPragmaDeclaration *sagePragma = isSgPragmaDeclaration (*i);
      ROSE_ASSERT (sagePragma);
      ROSE_ASSERT (sagePragma->get_pragma () != NULL);
      ROSE_ASSERT (sagePragma->get_pragma ()->get_pragma ());

      ControlStructureContainer *container = new ControlStructureContainer ();
      container->setPragmaString (sagePragma->get_pragma ()->get_pragma ());
      container->setAssociatedStatement (sagePragma);
      returnList.push_back (container);
    }
*/

  //find all statements in the current scope
  if (sageScopeStatement->variantT () == V_SgClassDefinition)
    {
      SgDeclarationStatementPtrList statementsInScope =
	sageScopeStatement->getDeclarationList ();
      SgDeclarationStatementPtrList::iterator i;
      for (i = statementsInScope.begin (); i != statementsInScope.end (); i++)
	{

	  SgLocatedNode *locatedNode = isSgLocatedNode (*i);
	  ROSE_ASSERT (locatedNode != NULL);

	  //find all comments attached to current node.
	  AttachedPreprocessingInfoType *comments =
	    locatedNode->getAttachedPreprocessingInfo ();


	  if(locatedNode->variantT() == V_SgPragmaDeclaration){
       	          SgPragmaDeclaration* sagePragmaDeclaration = isSgPragmaDeclaration(locatedNode);
	          ROSE_ASSERT( sagePragmaDeclaration );
	          ROSE_ASSERT( sagePragmaDeclaration->get_pragma() != NULL ); 
                  string pragmaDeclarationString =  sagePragmaDeclaration->get_pragma()->get_pragma();
                  //extract the part before the leftmost = is pragmaDeclarationString
	          pragmaDeclarationString = pragmaDeclarationString.substr(0,pragmaDeclarationString.find("="));
	          //if the name-criteria is met accept node
	         if(pragmaDeclarationString.find( stringToMatch ) != string::npos ){
	         	cout << pragmaDeclarationString << endl;
                        ControlStructureContainer *container = new ControlStructureContainer ();
                        container->setPragmaString (sagePragmaDeclaration->get_pragma ()->get_pragma ());
                        container->setAssociatedStatement (sagePragmaDeclaration);
                        returnList.push_back (container);
	         }
	  }
		  
	  
	  if (comments != NULL)
	    {
	      //We need to find comments which fits the criteria    
	      printf ("Found attached comments (at %p of type: %s): \n",
		      locatedNode, locatedNode->sage_class_name ());
	      AttachedPreprocessingInfoType::iterator j;
	      for (j = comments->begin (); j != comments->end (); j++)
		{
		  ROSE_ASSERT ((*j) != NULL);
		  string comment = (*j)->getString ();
		  //see if comment begins with stringPrefixToMatch
		  string tempString = comment.substr (0, comment.find (' '));
		  if (tempString == stringPrefixToMatch)
		    {		//+stringPrefixToMatch ){
		      //cout << "Found string" << endl;

		      comment =
			StringUtility::copyEdit (comment, stringPrefixToMatch,
						 "");

		      //see if the comment has an element which matches the stringToMatch
		      if (comment.find (stringToMatch) != string::npos)
			{
			  //puit the matching comment into a container    
			  ControlStructureContainer *container =
			    new ControlStructureContainer ();
			  container->setPragmaString (comment);
			  container->setAssociatedStatement (locatedNode);

			  returnList.push_back (container);
			}
		    }
//                printf ("          Attached Comment (relativePosition=%s):\n %s\n Next comment: \n",
//                    ((*j)->relativePosition == PreprocessingInfo::before) ? "before" : "after",(*j)->getString());

		}
	    }
	}
    }
  else
    {
      // AS 12/18/03 PS!! The same as the above, but a different iterator. Will replace this when a
      // different solution has arisen. PS!! 
      SgStatementPtrList statementsInScope =
	sageScopeStatement->getStatementList ();
      SgStatementPtrList::iterator i;

      for (i = statementsInScope.begin (); i != statementsInScope.end (); i++)
	{

	  SgLocatedNode *locatedNode = isSgLocatedNode (*i);
	  ROSE_ASSERT (locatedNode != NULL);

	  if(locatedNode->variantT() == V_SgPragmaDeclaration){
       	          SgPragmaDeclaration* sagePragmaDeclaration = isSgPragmaDeclaration(locatedNode);
	          ROSE_ASSERT( sagePragmaDeclaration );
	          ROSE_ASSERT( sagePragmaDeclaration->get_pragma() != NULL ); 
                  string pragmaDeclarationString =  sagePragmaDeclaration->get_pragma()->get_pragma();
                  //extract the part before the leftmost = is pragmaDeclarationString
	          pragmaDeclarationString = pragmaDeclarationString.substr(0,pragmaDeclarationString.find("="));
	          //if the name-criteria is met accept node
	         if(pragmaDeclarationString.find( stringToMatch ) != string::npos ){
	         	cout << pragmaDeclarationString << endl;
                        ControlStructureContainer *container = new ControlStructureContainer ();
                        container->setPragmaString (sagePragmaDeclaration->get_pragma ()->get_pragma ());
                        container->setAssociatedStatement (sagePragmaDeclaration);
                        returnList.push_back (container);
	         }
	  }

	  //find all comments attached to current node.
	  AttachedPreprocessingInfoType *comments =
	    locatedNode->getAttachedPreprocessingInfo ();

	  if (comments != NULL)
	    {
	      //We need to find comments which fits the criteria    
	      //printf ("Found attached comments (at %p of type: %s): \n",locatedNode,locatedNode->sage_class_name());
	      AttachedPreprocessingInfoType::iterator j;
	      for (j = comments->begin (); j != comments->end (); j++)
		{
		  ROSE_ASSERT ((*j) != NULL);
		  string comment = (*j)->getString ();
		  //see if comment begins with stringPrefixToMatch
		  string tempString = comment.substr (0, comment.find (' '));
		  if (tempString == stringPrefixToMatch)
		    {		//+stringPrefixToMatch ){
		      comment =
			StringUtility::copyEdit (comment, stringPrefixToMatch,
						 "");

		      cout << "And the string is: " << comment << endl;

		      if (comment.find (stringToMatch) != string::npos)
			{
			  cout << "And even the string is matched." << endl;
			  //ROSE_ASSERT(comment.find('=') != comment.length());
			  //string variableName = comment.substr(comment.find(stringToMatch), comment.find('='));
			  cout << "And the string is a match" << endl;


			  //puit the matching comment into a container    
			  ControlStructureContainer *container =
			    new ControlStructureContainer ();
			  container->setPragmaString (comment);
			  container->setAssociatedStatement (locatedNode);

			  returnList.push_back (container);
			}
		    }
		 /* printf
		    ("          Attached Comment (relativePosition=%s):\n %s\n Next comment: \n",
		     ((*j)->relativePosition ==
		      PreprocessingInfo::before) ? "before" : "after",
		     (*j)->getString ());*/

		}
	    }
	}

    }
  return returnList;
}				/* End function:  queryFindCommentsInScope() */