Example #1
0
    def associated_decl_creators(self, creator):
        """ references to all class declaration code creators. """
        if not isinstance(creator, code_creators.registration_based_t):
            return []

        associated_creators = creator.associated_decl_creators[:]

        internal_creators = []
        if isinstance(creator, code_creators.compound_t):
            internal_creators.extend([
                creator
                for creator in code_creators.make_flatten(creator.creators)
                if isinstance(creator, code_creators.registration_based_t)
            ])

        for internal_creator in internal_creators:
            associated_creators.extend(
                internal_creator.associated_decl_creators)
        #now associated_creators contains all code creators associated with the creator
        #We should leave only creators, defined in the global namespace
        associated_creators = [
            associated_creator for associated_creator in associated_creators
            if associated_creator.parent is self.extmodule
        ]
        return associated_creators
Example #2
0
 def test(self):
     mb = module_builder.module_builder_t(
             [ module_builder.create_text_fc( 'namespace enums{ enum { OK=1 }; }' ) ]
             , gccxml_path=autoconfig.gccxml.executable )
     mb.namespace( name='::enums' ).include()
     mb.build_code_creator('dummy')
     flatten = code_creators.make_flatten(mb.code_creator.creators)
     self.failUnless( filter( lambda inst: isinstance( inst, code_creators.unnamed_enum_t ), flatten ) )
Example #3
0
 def test(self):
     mb = module_builder.module_builder_t(
             [ module_builder.create_text_fc( 'namespace enums{ enum { OK=1 }; }' ) ]
             , gccxml_path=autoconfig.gccxml.executable
             , compiler=pygccxml.utils.native_compiler.get_gccxml_compiler() )
     mb.namespace( name='::enums' ).include()
     mb.build_code_creator('dummy')
     flatten = code_creators.make_flatten(mb.code_creator.creators)
     self.failUnless( [inst for inst in flatten if isinstance( inst, code_creators.unnamed_enum_t )] )
 def test(self):
     mb = module_builder.module_builder_t([
         module_builder.create_text_fc('namespace enums{ enum { OK=1 }; }')
     ],
                                          xml_generator_config=autoconfig.
                                          xml_generator_config)
     mb.namespace(name='::enums').include()
     mb.build_code_creator('dummy')
     flatten = code_creators.make_flatten(mb.code_creator.creators)
     self.assertTrue([
         inst for inst in flatten
         if isinstance(inst, code_creators.unnamed_enum_t)
     ])
Example #5
0
    def associated_decl_creators( self, creator ):
        """ references to all class declaration code creators. """
        if not isinstance( creator, code_creators.registration_based_t ):
            return []

        associated_creators = creator.associated_decl_creators[:]

        internal_creators = []
        if isinstance( creator, code_creators.compound_t ):
            internal_creators.extend(
                [creator for creator in code_creators.make_flatten( creator.creators ) if isinstance( creator, code_creators.registration_based_t )] )

        for internal_creator in internal_creators:
            associated_creators.extend( internal_creator.associated_decl_creators )
        #now associated_creators contains all code creators associated with the creator
        #We should leave only creators, defined in the global namespace
        associated_creators = [associated_creator for associated_creator in associated_creators if associated_creator.parent is self.extmodule]
        return associated_creators
Example #6
0
    def associated_decl_creators( self, creator ):
        """ references to all class declaration code creators. """
        if not isinstance( creator, code_creators.registration_based_t ):
            return []

        associated_creators = creator.associated_decl_creators[:]

        internal_creators = []
        if isinstance( creator, code_creators.compound_t ):
            internal_creators.extend(
                filter( lambda creator: isinstance( creator, code_creators.registration_based_t )
                        , code_creators.make_flatten( creator.creators ) ) )

        map( lambda internal_creator: associated_creators.extend( internal_creator.associated_decl_creators )
             , internal_creators )
        #now associated_creators contains all code creators associated with the creator
        #We should leave only creators, defined in the global namespace
        associated_creators = filter( lambda associated_creator: associated_creator.parent is self.extmodule
                                      , associated_creators )
        return associated_creators
Example #7
0
   def writeModule(self, moduleName=None, filename=None, useScope=None, 
                    multiFile=None, multiCreateMain=True):
      """ Create the module and write it out.
          Automatically calls createCreators() and filterExposed() if needed.
          
          @param moduleName: The name of the module being created.
          @param filename:   The file or directory to create the code.
          @param useScope:   If true the creators all use scope in their code.
          @param multiFile:  If true use the multifile writer.
          @param multiCreateMain: If true and using multifile then create main reg method.
      """
      if not self.mExtModule:
         self.buildCreators(moduleName, filename, useScope)
      extmodule = self.mExtModule
      assert extmodule

      startTime = time.time()

      if filename==None:
         filename = self.mOutput
      if multiFile==None:
         multiFile = self.mMultiFile

      # Check for missing policies...
      if self.mVerbose:
         print "Sanity check..."
      creators = code_creators.make_flatten(self.mExtModule)
      fmfunctions = filter(lambda creator: isinstance(creator, code_creators.calldef.calldef_t) and not isinstance(creator, code_creators.calldef.constructor_t), creators)
      missing_flag = False
      sanity_failed = []
      for creator in fmfunctions:
         if not creator.declaration.call_policies:
            print "Missing policy:", declarations.full_name(creator.declaration)
            missing_flag = True
         if not self._declSanityCheck(creator.declaration):
            sanity_failed.append(creator.declaration)
      if len(sanity_failed)>0:
         f = file("problems.log", "wt")
         print "***Warning*** The following %d declarations may produce code that compiles, but"%len(sanity_failed)
         print >>f, "***Warning*** The following %d declarations may produce code that compiles, but"%len(sanity_failed)
         print "that does not have the desired effect in Python:"
         print >>f, "that does not have the desired effect in Python:"
         for decl in sanity_failed:
            print " ",decl
            print >>f, " ",decl
            print >>f, "  ",decl.location.line, decl.location.file_name
      if missing_flag:
         print "*** Aborting because of missing policies!"
         return
      
      if self.mVerbose:
         print "Writing out files (%s)..."%filename
      
      # Write out the file(s)
      if not multiFile:
         file_writers.write_file(extmodule, filename)
         # Let the arg policy manager write its files...
         self.mArgPolicyManager.writeFiles(os.path.dirname(filename))
      else:
         mfs = file_writers.multiple_files_t(extmodule, filename, write_main=multiCreateMain)
         mfs.write()
         self.split_header_names = mfs.split_header_names
         self.split_method_names = mfs.split_method_names

         # Let the arg policy manager write its files...
         self.mArgPolicyManager.writeFiles(filename)
         
      if self.mVerbose:
         print "Module written in %s"%self._time2str(time.time()-startTime)
         print "Module generation complete."
         print "Total time: %s"%self._time2str(time.time()-self.mStartTime)
Example #8
0
   def buildCreators(self, moduleName=None, filename=None, useScope=None):
      """ Build creator tree and module from the current declarations.
          See writeModule for parameter documentation.
          In normal usage the user will not call this directly.
          Return the base of the creator tree.

          @rtype: module_t
      """
      if None == self.mDeclRoot:
         self.parse()

      if self.mVerbose:
         print "Decoration time:",self._time2str(time.time()-self.mParseEndTime)
      startTime = time.time()

      if moduleName==None:
         moduleName = self.mModuleName
      if moduleName==None:
         raise ValueError, "No output module name given"
      if useScope==None:
         useScope = self.mUseScope

      # Lock the decoration interface (an attempt to decorate after this
      # call will lead to an error)
      declwrapper.decl_lock = True
      
      if self.mVerbose:
         print "Creating module code creator tree...."
         
      # Filter the exposed decl list to create a final decl list.      
#      def filter(decl):
#         expose = getattr(decl, "_expose_flag", False)
#         return expose
      
#      if self.mVerbose:
#         print "Filtering module..."
         
#      self.mFinalDecls = declarations.filtering.user_defined( self.mDeclRoot, filter)

      # The above filtering is already done in pyplusplus as it stores
      # the "ignore" flag itself. [mbaas]
         
      # Create creator.module_t for the module
      # - override the header files in create since we already know what files we used.
      maker = module_creator.creator_t(self.mDeclRoot, module_name=moduleName)      
#      maker = module_creator.creator_t(self.mFinalDecls, module_name=moduleName)      
      extmodule = maker.create(decl_headers=self.mHeaderFiles)

      # Preprocess the tree
      self._preprocessCreatorTree(extmodule)

      # Let the arg policy manager update the tree...
      self.mArgPolicyManager.updateCreators(extmodule)

      # Handle the extra creators that need added
      mod_body = extmodule.body
      for c in self.mBodyTailCreators:
         mod_body.adopt_creator(c)
      
      for c in self.mEndCreators:
         extmodule.adopt_creator(c)
         
      self.mStartCreators.reverse()
      for c in self.mStartCreators:
         extmodule.adopt_creator(c, extmodule.last_include_index()+1)
         
      for h in self.mExtraIncludes:
         extmodule.adopt_include(code_creators.include_t(h))
         
      if useScope:
         class_creators = filter( lambda c: isinstance( c, code_creators.class_t )
                                 , code_creators.make_flatten( extmodule.body.creators ) )
         for c in class_creators:
            c.always_expose_using_scope = True #better error reporting from compiler   
      
      if self.mLicense:
         extmodule._set_license(self.mLicense)

      if self.mVerbose:
         print "Code creator tree built in %s"%self._time2str(time.time()-startTime)
         
      self.mExtModule = extmodule
      return self.mExtModule
Example #9
0
        accessors_db[ property_name ][ int(creator.declaration.name[0] == 's') ] = creator
    #Now, when we have all pairs of accessors, we can actually start replacing them
    #with instance of property_creator_t
    for get_creator, set_creator in accessors_db.values():
        if not ( get_creator and set_creator ):
            continue 
        #removing get/set code creators
        class_creator.remove_creator( get_creator )
        class_creator.remove_creator( set_creator )
        #instead of them we add an instance of property_creator_t class
        prop_creator = property_creator_t( get_creator.declaration, set_creator.declaration )
        class_creator.adopt_creator( prop_creator )

if __name__ == '__main__':
    module_name = 'properties'
    #1. creating module builder
    mb = module_builder.module_builder_t( files=['properties.hpp']
                                          , gccxml_path=gccxml.executable )
    #2. creating module code creator
    mb.build_code_creator( module_name=module_name )    
    mb.code_creator.user_defined_directories.append( os.path.abspath( '.' ) )
    
    #3. replacing get/set code creators with property code creator
    classes = filter( lambda creator: isinstance( creator, code_creators.class_t )
                      , code_creators.make_flatten( mb.code_creator ) )
    map( replace_functions, classes )
    
    #4. writing module to disk
    mb.write_module( os.path.join( os.path.abspath( '.' ), 'generated', module_name + '.py.cpp') )

    print 'done'
Example #10
0
    def writeModule(self,
                    moduleName=None,
                    filename=None,
                    useScope=None,
                    multiFile=None,
                    multiCreateMain=True):
        """ Create the module and write it out.
          Automatically calls createCreators() and filterExposed() if needed.
          
          @param moduleName: The name of the module being created.
          @param filename:   The file or directory to create the code.
          @param useScope:   If true the creators all use scope in their code.
          @param multiFile:  If true use the multifile writer.
          @param multiCreateMain: If true and using multifile then create main reg method.
      """
        if not self.mExtModule:
            self.buildCreators(moduleName, filename, useScope)
        extmodule = self.mExtModule
        assert extmodule

        startTime = time.time()

        if filename == None:
            filename = self.mOutput
        if multiFile == None:
            multiFile = self.mMultiFile

        # Check for missing policies...
        if self.mVerbose:
            print "Sanity check..."
        creators = code_creators.make_flatten(self.mExtModule)
        fmfunctions = filter(
            lambda creator: isinstance(
                creator, code_creators.calldef.calldef_t) and not isinstance(
                    creator, code_creators.calldef.constructor_t), creators)
        missing_flag = False
        sanity_failed = []
        for creator in fmfunctions:
            if not creator.declaration.call_policies:
                print "Missing policy:", declarations.full_name(
                    creator.declaration)
                missing_flag = True
            if not self._declSanityCheck(creator.declaration):
                sanity_failed.append(creator.declaration)
        if len(sanity_failed) > 0:
            f = file("problems.log", "wt")
            print "***Warning*** The following %d declarations may produce code that compiles, but" % len(
                sanity_failed)
            print >> f, "***Warning*** The following %d declarations may produce code that compiles, but" % len(
                sanity_failed)
            print "that does not have the desired effect in Python:"
            print >> f, "that does not have the desired effect in Python:"
            for decl in sanity_failed:
                print " ", decl
                print >> f, " ", decl
                print >> f, "  ", decl.location.line, decl.location.file_name
        if missing_flag:
            print "*** Aborting because of missing policies!"
            return

        if self.mVerbose:
            print "Writing out files (%s)..." % filename

        # Write out the file(s)
        if not multiFile:
            file_writers.write_file(extmodule, filename)
            # Let the arg policy manager write its files...
            self.mArgPolicyManager.writeFiles(os.path.dirname(filename))
        else:
            mfs = file_writers.multiple_files_t(extmodule,
                                                filename,
                                                write_main=multiCreateMain)
            mfs.write()
            self.split_header_names = mfs.split_header_names
            self.split_method_names = mfs.split_method_names

            # Let the arg policy manager write its files...
            self.mArgPolicyManager.writeFiles(filename)

        if self.mVerbose:
            print "Module written in %s" % self._time2str(time.time() -
                                                          startTime)
            print "Module generation complete."
            print "Total time: %s" % self._time2str(time.time() -
                                                    self.mStartTime)
Example #11
0
    def buildCreators(self, moduleName=None, filename=None, useScope=None):
        """ Build creator tree and module from the current declarations.
          See writeModule for parameter documentation.
          In normal usage the user will not call this directly.
          Return the base of the creator tree.

          @rtype: module_t
      """
        if None == self.mDeclRoot:
            self.parse()

        if self.mVerbose:
            print "Decoration time:", self._time2str(time.time() -
                                                     self.mParseEndTime)
        startTime = time.time()

        if moduleName == None:
            moduleName = self.mModuleName
        if moduleName == None:
            raise ValueError, "No output module name given"
        if useScope == None:
            useScope = self.mUseScope

        # Lock the decoration interface (an attempt to decorate after this
        # call will lead to an error)
        declwrapper.decl_lock = True

        if self.mVerbose:
            print "Creating module code creator tree...."

        # Filter the exposed decl list to create a final decl list.


#      def filter(decl):
#         expose = getattr(decl, "_expose_flag", False)
#         return expose

#      if self.mVerbose:
#         print "Filtering module..."

#      self.mFinalDecls = declarations.filtering.user_defined( self.mDeclRoot, filter)

# The above filtering is already done in pyplusplus as it stores
# the "ignore" flag itself. [mbaas]

# Create creator.module_t for the module
# - override the header files in create since we already know what files we used.
        maker = module_creator.creator_t(self.mDeclRoot,
                                         module_name=moduleName)
        #      maker = module_creator.creator_t(self.mFinalDecls, module_name=moduleName)
        extmodule = maker.create(decl_headers=self.mHeaderFiles)

        # Preprocess the tree
        self._preprocessCreatorTree(extmodule)

        # Let the arg policy manager update the tree...
        self.mArgPolicyManager.updateCreators(extmodule)

        # Handle the extra creators that need added
        mod_body = extmodule.body
        for c in self.mBodyTailCreators:
            mod_body.adopt_creator(c)

        for c in self.mEndCreators:
            extmodule.adopt_creator(c)

        self.mStartCreators.reverse()
        for c in self.mStartCreators:
            extmodule.adopt_creator(c, extmodule.last_include_index() + 1)

        for h in self.mExtraIncludes:
            extmodule.adopt_include(code_creators.include_t(h))

        if useScope:
            class_creators = filter(
                lambda c: isinstance(c, code_creators.class_t),
                code_creators.make_flatten(extmodule.body.creators))
            for c in class_creators:
                c.always_expose_using_scope = True  #better error reporting from compiler

        if self.mLicense:
            extmodule._set_license(self.mLicense)

        if self.mVerbose:
            print "Code creator tree built in %s" % self._time2str(
                time.time() - startTime)

        self.mExtModule = extmodule
        return self.mExtModule