Пример #1
0
def AutoExclude( mb ):
    """ Automaticaly exclude a range of things that don't convert well from C++ to Python
    """
    global_ns = mb.global_ns
    for ns in NAMESPACES:
        main_ns = global_ns.namespace( ns )
    
        # vars that are static consts but have their values set in the header file are bad
        Remove_Static_Consts ( main_ns )
        
        ## Exclude protected and private that are not pure virtual
        query = declarations.access_type_matcher_t( 'private' ) \
                & ~declarations.virtuality_type_matcher_t( declarations.VIRTUALITY_TYPES.PURE_VIRTUAL )
        try:
            non_public_non_pure_virtual = main_ns.calldefs( query )
            non_public_non_pure_virtual.exclude()
        except:
            pass
    
        #Virtual functions that return reference could not be overriden from Python
        query = declarations.virtuality_type_matcher_t( declarations.VIRTUALITY_TYPES.VIRTUAL ) \
                & declarations.custom_matcher_t( lambda decl: declarations.is_reference( decl.return_type ) )
        try:
            main_ns.calldefs( query ).virtuality = declarations.VIRTUALITY_TYPES.NOT_VIRTUAL
        except:
            pass
Пример #2
0
    def parse(self):

        xml_generator_config = parser.xml_generator_configuration_t(xml_generator_path=self.castxml_binary, 
                                                                    xml_generator="castxml",
                                                                    cflags="-std=c++11",
                                                                    include_paths=self.source_includes)

        print ("INFO: Parsing Code")
        decls = parser.parse([self.wrapper_header_collection], xml_generator_config,
                             compilation_mode=parser.COMPILATION_MODE.ALL_AT_ONCE)

        # Get access to the global namespace
        self.global_ns = declarations.get_global_namespace(decls)

        # Clean decls to only include those for which file locations exist
        print ("INFO: Cleaning Decls")
        query = declarations.custom_matcher_t(lambda decl: decl.location is not None)
        decls_loc_not_none = self.global_ns.decls(function=query)

        # Identify decls in our source tree
        def check_loc(loc):
            return (self.source_root in loc) or ("wrapper_header_collection" in loc)
        
        source_decls = [decl for decl in decls_loc_not_none if check_loc(decl.location.file_name)]
        self.source_ns = declarations.namespace_t("source", source_decls)

        print ("INFO: Optimizing Decls")
        self.source_ns.init_optimizer()
Пример #3
0
def AutoExclude( mb ):
    """ Automaticaly exclude a range of things that don't convert well from C++ to Python
    """
    global_ns = mb.global_ns
    main_ns = global_ns   # No namespaces in NxPhysics


    #Virtual functions that return reference could not be overriden from Python
    query = declarations.virtuality_type_matcher_t( declarations.VIRTUALITY_TYPES.VIRTUAL ) \
            & declarations.custom_matcher_t( lambda decl: declarations.is_reference( decl.return_type ) )
    try:
        main_ns.calldefs( query ).virtuality = declarations.VIRTUALITY_TYPES.NOT_VIRTUAL
    except:
        pass
Пример #4
0
    def redefined_funcs( self ):
        """
        returns list of member functions that should be defined in the class wrapper

        It comes useful in 3 tier hierarchy:

        .. code-block:: c++

           struct base{
               virtual void do_nothing() = 0;
           };

           struct derived{
               virtual void do_something() = 0;
           };

           struct concrete{
               virtual void do_nothing(){}
               virtual void do_something(){}
           };

        The wrapper for class `derived`, should define `do_nothing` function,
        otherwise the generated code will not compile
        """

        if isinstance( self._redefined_funcs, list ):
            return self._redefined_funcs

        all_included = declarations.custom_matcher_t( lambda decl: decl.ignore == False and decl.exportable )
        all_protected = declarations.access_type_matcher_t( 'protected' ) & all_included
        all_pure_virtual = declarations.virtuality_type_matcher_t( VIRTUALITY_TYPES.PURE_VIRTUAL )
        all_virtual = declarations.virtuality_type_matcher_t( VIRTUALITY_TYPES.VIRTUAL ) \
                      & ( declarations.access_type_matcher_t( 'public' ) \
                          | declarations.access_type_matcher_t( 'protected' ))
        all_not_pure_virtual = ~all_pure_virtual

        query = all_protected | all_pure_virtual
        mf_query = query | all_virtual
        relevant_opers = declarations.custom_matcher_t( lambda decl: decl.symbol in ('()', '[]') )
        funcs = []
        defined_funcs = []

        for base in self.recursive_bases:
            if base.access == ACCESS_TYPES.PRIVATE:
                continue
            base_cls = base.related_class

            funcs.extend( base_cls.member_functions( mf_query, recursive=False, allow_empty=True ) )
            funcs.extend( base_cls.member_operators( relevant_opers & query, recursive=False, allow_empty=True ) )

            defined_funcs.extend( base_cls.member_functions( all_not_pure_virtual, recursive=False, allow_empty=True ) )
            defined_funcs.extend( base_cls.member_operators( all_not_pure_virtual & relevant_opers, recursive=False, allow_empty=True ) )

        not_reimplemented_funcs = set()
        is_same_function = declarations.is_same_function
        for f in funcs:
            cls_fs = self.calldefs( name=f.name, recursive=False, allow_empty=True )
            for cls_f in cls_fs:
                if is_same_function( f, cls_f ):
                    break
            else:
                #should test whether this function has been added or not
                for f_impl in not_reimplemented_funcs:
                    if is_same_function( f, f_impl ):
                        if declarations.is_base_and_derived( f_impl.parent, f.parent ):
                            #add function from the most derived class
                            not_reimplemented_funcs.remove( f_impl )
                            not_reimplemented_funcs.add( f )
                        break
                else:
                    #should test whether this function is implemented in base class
                    if f.virtuality != VIRTUALITY_TYPES.PURE_VIRTUAL:
                        not_reimplemented_funcs.add( f )
                    else:
                        for f_defined in defined_funcs:
                            if is_same_function( f, f_defined ):
                                break
                        else:
                            not_reimplemented_funcs.add( f )
        functions = [f for f in list( not_reimplemented_funcs ) if ( False == f.ignore and True == f.exportable )
                                      or all_pure_virtual( f )]


        #Boost.Python is not able to call for non-virtual function, from the base
        #class if there is a virtual function with the same within base class
        #See override_bug tester for more information

        def buggy_bpl_filter( f ):
            if f.parent is self:
                return False
            if f.access_type != ACCESS_TYPES.PUBLIC:
                return False
            if f.virtuality != VIRTUALITY_TYPES.NOT_VIRTUAL:
                return False
            #we need to check that we don't have "same" function in this class
            this_funs = self.decls( name=f.name
                                    , decl_type=declarations.calldef_t
                                    , recursive=False
                                    , allow_empty=True )
            for this_f in this_funs:
                if is_same_function( this_f, f ):
                    #there is already the function in the class, so no need to redefined it
                    return False
            else:
                return True

        tmp = {} # id : f
        for redefined_f in functions:
            #redefined is virtual, I am not interested in virtual functions
            for rfo in redefined_f.overloads:
                if id(rfo) in tmp:
                    continue
                if buggy_bpl_filter( rfo ):
                    tmp[ id(rfo) ] = rfo
        functions.extend( list(tmp.values()) )

        functions.sort( key=lambda f: ( f.name, f.location.as_tuple() ) )

        self._redefined_funcs = functions
        return self._redefined_funcs
    def redefined_funcs( self ):
        """returns list of member functions that should be defined in class wrapper

        It comes useful in 3 tier hierarchy:
        struct base{
            virtual void do_nothing() = 0;
        };

        struct derived{
            virtual void do_something() = 0;
        };

        struct concrete{
            virtual void do_nothing(){}
            virtual void do_something(){}
        };

        derived_wrapper should define do_nothing function, otherwise the generated
        code will not compile
        """

        if isinstance( self._redefined_funcs, list ):
            return self._redefined_funcs

        all_included = declarations.custom_matcher_t( lambda decl: decl.ignore == False and decl.exportable )
        all_protected = declarations.access_type_matcher_t( 'protected' ) & all_included
        all_pure_virtual = declarations.virtuality_type_matcher_t( VIRTUALITY_TYPES.PURE_VIRTUAL )
        all_not_pure_virtual = ~all_pure_virtual

        query = all_protected | all_pure_virtual
        relevant_opers = declarations.custom_matcher_t( lambda decl: decl.symbol in ('()', '[]') )
        funcs = set()
        defined_funcs = set()

        for base in self.recursive_bases:
            if base.access == ACCESS_TYPES.PRIVATE:
                continue
            base_cls = base.related_class
            funcs.update( base_cls.member_functions( query, recursive=False, allow_empty=True ) )
            funcs.update( base_cls.member_operators( relevant_opers & query, recursive=False, allow_empty=True ) )

            defined_funcs.update( base_cls.member_functions( all_not_pure_virtual, recursive=False, allow_empty=True ) )
            defined_funcs.update( base_cls.member_operators( all_not_pure_virtual & relevant_opers, recursive=False, allow_empty=True ) )

        not_reimplemented_funcs = set()
        is_same_function = declarations.is_same_function
        for f in funcs:
            cls_fs = self.calldefs( name=f.name, recursive=False, allow_empty=True )
            for cls_f in cls_fs:
                if is_same_function( f, cls_f ):
                    break
            else:
                #should test whether this function has been added or not
                for f_impl in not_reimplemented_funcs:
                    if is_same_function( f, f_impl ):
                        if declarations.is_base_and_derived( f_impl.parent, f.parent ):
                            #add function from the most derived class
                            not_reimplemented_funcs.remove( f_impl )
                            not_reimplemented_funcs.add( f )                       
                        break
                else:
                    #should test whether this function is implemented in base class
                    if f.virtuality != VIRTUALITY_TYPES.PURE_VIRTUAL:
                        not_reimplemented_funcs.add( f )
                    else:
                        for f_defined in defined_funcs:
                            if is_same_function( f, f_defined ):
                                break
                        else:
                            not_reimplemented_funcs.add( f )
        functions = list( not_reimplemented_funcs )
        functions.sort( cmp=lambda f1, f2: cmp( ( f1.name, f1.location.as_tuple() )
                                                , ( f2.name, f2.location.as_tuple() ) ) )
        self._redefined_funcs = functions
        return self._redefined_funcs
Пример #6
0
    def get_header_info(self):
        """
        PyGCCXML header code parser
        magic happens here!
        : returns the parsed header data in python dict
        : return dict keys: namespace, class, io_signature, make,
                       properties, methods
        : Can be used as an CLI command or an external API
        """
        gr = self.modname.split('-')[0]
        module = self.modname.split('-')[-1]
        self.parsed_data['module_name'] = module
        generator_path, generator_name = utils.find_xml_generator()
        xml_generator_config = parser.xml_generator_configuration_t(
            xml_generator_path=generator_path,
            xml_generator=generator_name,
            include_paths=self.include_paths,
            compiler='gcc',
            define_symbols=['BOOST_ATOMIC_DETAIL_EXTRA_BACKEND_GENERIC'],
            cflags='-std=c++11')
        decls = parser.parse([self.target_file], xml_generator_config)
        global_namespace = declarations.get_global_namespace(decls)

        # namespace
        try:
            self.parsed_data['namespace'] = []
            ns = global_namespace.namespace(gr)
            if ns is None:
                raise BlockToolException
            main_namespace = ns.namespace(module)
            if main_namespace is None:
                raise BlockToolException('namespace cannot be none')
            self.parsed_data['namespace'] = [gr, module]
            if main_namespace.declarations:
                for _namespace in main_namespace.declarations:
                    if isinstance(_namespace, declarations.namespace_t):
                        if Constants.KERNEL not in str(_namespace):
                            main_namespace = _namespace
                            self.parsed_data['namespace'].append(
                                str(_namespace).split('::')[-1].split(' ')[0])
        except RuntimeError:
            raise BlockToolException(
                'Invalid namespace format in the block header file')

        # class
        try:
            self.parsed_data['class'] = ''
            for _class in main_namespace.declarations:
                if isinstance(_class, declarations.class_t):
                    expected_class_name = self.filename.split('.')[0]
                    if expected_class_name in str(_class):
                        main_class = _class
                        self.parsed_data['class'] = str(_class).split(
                            '::')[2].split(' ')[0]
                        # in more complicated blocks, there are many classes included in this declaration
                        # Break after the first class - safe to assume this is the "main class"?
                        if len(main_class.bases) > 0:
                            self.parsed_data['block_type'] = main_class.bases[
                                0].declaration_path[-1]
                            break
        except RuntimeError:
            raise BlockToolException(
                'Block header namespace {} must consist of a valid class instance'
                .format(module))

        # io_signature, message_ports
        self.parsed_data['io_signature'] = {}
        self.parsed_data['message_port'] = {}
        if os.path.isfile(self.impl_file) and exist_comments(self):
            self.parsed_data['io_signature'] = io_signature(self.impl_file)
            self.parsed_data['message_port'] = message_port(self.impl_file)
            read_comments(self)
        elif os.path.isfile(self.impl_file) and not exist_comments(self):
            self.parsed_data['io_signature'] = io_signature(self.impl_file)
            self.parsed_data['message_port'] = message_port(self.impl_file)
            if self.addcomments:
                add_comments(self)
        elif not os.path.isfile(self.impl_file) and exist_comments(self):
            read_comments(self)
        else:
            self.parsed_data['io_signature'] = {"input": [], "output": []}
            self.parsed_data['message_port'] = self.parsed_data['io_signature']

        # make
        try:
            self.parsed_data['make'] = {}
            self.parsed_data['make']['arguments'] = []
            query_m = declarations.custom_matcher_t(
                lambda mem_fun: mem_fun.name.startswith('make'))
            query_make = query_m & declarations.access_type_matcher_t('public')
            make_func = main_class.member_functions(
                function=query_make,
                allow_empty=True,
                header_file=self.target_file)
            criteria = declarations.calldef_matcher(name='make')
            _make_fun = declarations.matcher.get_single(criteria, main_class)
            _make_fun = str(_make_fun).split('make')[-1].split(')')[0].split(
                '(')[1].lstrip().rstrip().split(',')
            if make_func:
                for arg in make_func[0].arguments:
                    make_arguments = None
                    '''
                    for _arg in _make_fun:
                        if str(arg.name) in _arg:
                            make_arguments = {
                                "name": str(arg.name),
                                "dtype": str(arg.decl_type),
                                "default": ""
                            }
                            if re.findall(r'[-+]?\d*\.\d+|\d+', _arg):
                                make_arguments['default'] = re.findall(
                                    r'[-+]?\d*\.\d+|\d+', _arg)[0]
                            elif re.findall(r'\"(.+?)\"', _arg):
                                make_arguments['default'] = re.findall(
                                    r'\"(.+?)\"', _arg)[0]
                            elif "true" in _arg:
                                make_arguments['default'] = "True"
                            elif "false" in _arg:
                                make_arguments['default'] = "False"
                    '''
                    # In case the search did not find an argument in the inner loop
                    # This happens while parsing digital/symbol_sync_cc.h
                    if make_arguments:
                        self.parsed_data['make']['arguments'].append(
                            make_arguments.copy())
                    else:
                        self.parsed_data['make']['arguments'].append({
                            "name":
                            str(arg.name),
                            "dtype":
                            str(arg.decl_type),
                            "default":
                            arg.
                            default_value  # can we get default argument directly from arg
                        })
        except RuntimeError:
            self.parsed_data['make'] = {}
            self.parsed_data['make']['arguments'] = []

        # setters
        try:
            self.parsed_data['methods'] = []
            query_methods = declarations.access_type_matcher_t('public')
            setters = main_class.member_functions(function=query_methods,
                                                  allow_empty=True,
                                                  header_file=self.target_file)
            getter_arguments = []
            if setters:
                for setter in setters:
                    if str(setter.name).startswith(
                            'set_') and setter.arguments:
                        setter_args = {
                            "name": str(setter.name),
                            "arguments_type": []
                        }
                        for argument in setter.arguments:
                            args = {
                                "name": str(argument.name),
                                "dtype": str(argument.decl_type)
                            }
                            getter_arguments.append(args['name'])
                            setter_args['arguments_type'].append(args.copy())
                        self.parsed_data['methods'].append(setter_args.copy())
        except RuntimeError:
            self.parsed_data['methods'] = []

        # getters
        try:
            self.parsed_data['properties'] = []
            query_properties = declarations.access_type_matcher_t('public')
            getters = main_class.member_functions(function=query_properties,
                                                  allow_empty=True,
                                                  header_file=self.target_file)
            if getters:
                for getter in getters:
                    if not getter.arguments or getter.has_const:
                        getter_args = {
                            "name": str(getter.name),
                            "dtype": str(getter.return_type),
                            "read_only": True
                        }
                        if getter_args['name'] in getter_arguments:
                            getter_args["read_only"] = False
                        self.parsed_data['properties'].append(
                            getter_args.copy())
        except RuntimeError:
            self.parsed_data['properties'] = []

        # all member functions
        # setters and getters do not return all member functions for a block
        try:
            self.parsed_data['member_functions'] = []
            query_methods = declarations.access_type_matcher_t('public')
            functions = main_class.member_functions(
                function=query_methods,
                allow_empty=True,
                header_file=self.target_file)
            if functions:
                for fcn in functions:
                    if str(fcn.name) not in [
                            main_class.name, '~' + main_class.name, 'make'
                    ]:
                        fcn_args = {"name": str(fcn.name), "arguments": []}
                        for argument in fcn.arguments:
                            args = {
                                "name": str(argument.name),
                                "dtype": str(argument.decl_type),
                                "default": argument.default_value
                            }
                            fcn_args['arguments'].append(args.copy())
                        self.parsed_data['member_functions'].append(
                            fcn_args.copy())
        except RuntimeError:
            self.parsed_data['member_functions'] = []

        # documentation
        try:
            _index = None
            header_file = codecs.open(self.target_file, 'r', 'cp932')
            self.parsed_data['docstring'] = re.compile(
                r'//.*?$|/\*.*?\*/',
                re.DOTALL | re.MULTILINE).findall(header_file.read())[2:]
            header_file.close()
            for doc in self.parsed_data['docstring']:
                if Constants.BLOCKTOOL in doc:
                    _index = self.parsed_data['docstring'].index(doc)
            if _index is not None:
                self.parsed_data['docstring'] = self.parsed_data[
                    'docstring'][:_index]
        except:
            self.parsed_data['docstring'] = []

        return self.parsed_data
Пример #7
0
    def redefined_funcs(self):
        """
        returns list of member functions that should be defined in the class wrapper

        It comes useful in 3 tier hierarchy:

        .. code-block:: c++

           struct base{
               virtual void do_nothing() = 0;
           };

           struct derived{
               virtual void do_something() = 0;
           };

           struct concrete{
               virtual void do_nothing(){}
               virtual void do_something(){}
           };

        The wrapper for class `derived`, should define `do_nothing` function,
        otherwise the generated code will not compile
        """

        if isinstance(self._redefined_funcs, list):
            return self._redefined_funcs

        all_included = declarations.custom_matcher_t(
            lambda decl: decl.ignore == False and decl.exportable)
        all_protected = declarations.access_type_matcher_t(
            'protected') & all_included
        all_pure_virtual = declarations.virtuality_type_matcher_t(
            VIRTUALITY_TYPES.PURE_VIRTUAL)
        all_virtual = declarations.virtuality_type_matcher_t( VIRTUALITY_TYPES.VIRTUAL ) \
                      & ( declarations.access_type_matcher_t( 'public' ) \
                          | declarations.access_type_matcher_t( 'protected' ))
        all_not_pure_virtual = ~all_pure_virtual

        query = all_protected | all_pure_virtual
        mf_query = query | all_virtual
        relevant_opers = declarations.custom_matcher_t(
            lambda decl: decl.symbol in ('()', '[]'))
        funcs = []
        defined_funcs = []

        for base in self.recursive_bases:
            if base.access == ACCESS_TYPES.PRIVATE:
                continue
            base_cls = base.related_class

            funcs.extend(
                base_cls.member_functions(mf_query,
                                          recursive=False,
                                          allow_empty=True))
            funcs.extend(
                base_cls.member_operators(relevant_opers & query,
                                          recursive=False,
                                          allow_empty=True))

            defined_funcs.extend(
                base_cls.member_functions(all_not_pure_virtual,
                                          recursive=False,
                                          allow_empty=True))
            defined_funcs.extend(
                base_cls.member_operators(all_not_pure_virtual
                                          & relevant_opers,
                                          recursive=False,
                                          allow_empty=True))

        not_reimplemented_funcs = set()
        is_same_function = declarations.is_same_function
        for f in funcs:
            cls_fs = self.calldefs(name=f.name,
                                   recursive=False,
                                   allow_empty=True)
            for cls_f in cls_fs:
                if is_same_function(f, cls_f):
                    break
            else:
                #should test whether this function has been added or not
                for f_impl in not_reimplemented_funcs:
                    if is_same_function(f, f_impl):
                        if declarations.is_base_and_derived(
                                f_impl.parent, f.parent):
                            #add function from the most derived class
                            not_reimplemented_funcs.remove(f_impl)
                            not_reimplemented_funcs.add(f)
                        break
                else:
                    #should test whether this function is implemented in base class
                    if f.virtuality != VIRTUALITY_TYPES.PURE_VIRTUAL:
                        not_reimplemented_funcs.add(f)
                    else:
                        for f_defined in defined_funcs:
                            if is_same_function(f, f_defined):
                                break
                        else:
                            not_reimplemented_funcs.add(f)
        functions = filter(
            lambda f: (False == f.ignore and True == f.exportable) or
            all_pure_virtual(f), list(not_reimplemented_funcs))

        #Boost.Python is not able to call for non-virtual function, from the base
        #class if there is a virtual function with the same within base class
        #See override_bug tester for more information

        def buggy_bpl_filter(f):
            if f.parent is self:
                return False
            if f.access_type != ACCESS_TYPES.PUBLIC:
                return False
            if f.virtuality != VIRTUALITY_TYPES.NOT_VIRTUAL:
                return False
            #we need to check that we don't have "same" function in this class
            this_funs = self.decls(name=f.name,
                                   decl_type=declarations.calldef_t,
                                   recursive=False,
                                   allow_empty=True)
            for this_f in this_funs:
                if is_same_function(this_f, f):
                    #there is already the function in the class, so no need to redefined it
                    return False
            else:
                return True

        tmp = {}  # id : f
        for redefined_f in functions:
            #redefined is virtual, I am not interested in virtual functions
            for rfo in redefined_f.overloads:
                if id(rfo) in tmp:
                    continue
                if buggy_bpl_filter(rfo):
                    tmp[id(rfo)] = rfo
        functions.extend(tmp.values())

        functions.sort(cmp=lambda f1, f2: cmp((f1.name, f1.location.as_tuple(
        )), (f2.name, f2.location.as_tuple())))

        self._redefined_funcs = functions
        return self._redefined_funcs
Пример #8
0
    def get_header_info(self):
        """
        PyGCCXML header code parser
        magic happens here!
        : returns the parsed header data in python dict
        : return dict keys: namespace, class, io_signature, make,
                       properties, methods
        : Can be used as an CLI command or an extenal API
        """
        gr = self.modname.split('-')[0]
        module = self.modname.split('-')[-1]
        generator_path, generator_name = utils.find_xml_generator()
        xml_generator_config = parser.xml_generator_configuration_t(
            xml_generator_path=generator_path,
            xml_generator=generator_name,
            compiler='gcc')
        decls = parser.parse(
            [self.target_file], xml_generator_config)
        global_namespace = declarations.get_global_namespace(decls)

        # namespace
        try:
            self.parsed_data['namespace'] = []
            ns = global_namespace.namespace(gr)
            if ns is None:
                raise BlockToolException
            main_namespace = ns.namespace(module)
            if main_namespace is None:
                raise BlockToolException('namespace cannot be none')
            self.parsed_data['namespace'] = [gr, module]
            if main_namespace.declarations:
                for _namespace in main_namespace.declarations:
                    if isinstance(_namespace, declarations.namespace_t):
                        if Constants.KERNEL not in str(_namespace):
                            main_namespace = _namespace
                            self.parsed_data['namespace'].append(
                                str(_namespace).split('::')[-1].split(' ')[0])
        except RuntimeError:
            raise BlockToolException(
                'Invalid namespace format in the block header file')

        # class
        try:
            self.parsed_data['class'] = ''
            for _class in main_namespace.declarations:
                if isinstance(_class, declarations.class_t):
                    main_class = _class
                    self.parsed_data['class'] = str(_class).split('::')[
                        2].split(' ')[0]
        except RuntimeError:
            raise BlockToolException(
                'Block header namespace {} must consist of a valid class instance'.format(module))

        # io_signature, message_ports
        self.parsed_data['io_signature'] = {}
        self.parsed_data['message_port'] = {}
        if os.path.isfile(self.impl_file) and exist_comments(self):
            self.parsed_data['io_signature'] = io_signature(
                self.impl_file)
            self.parsed_data['message_port'] = message_port(
                self.impl_file)
            read_comments(self)
        elif os.path.isfile(self.impl_file) and not exist_comments(self):
            self.parsed_data['io_signature'] = io_signature(
                self.impl_file)
            self.parsed_data['message_port'] = message_port(
                self.impl_file)
            if self.addcomments:
                add_comments(self)
        elif not os.path.isfile(self.impl_file) and exist_comments(self):
            read_comments(self)
        else:
            self.parsed_data['io_signature'] = {
                "input": [],
                "output": []
            }
            self.parsed_data['message_port'] = self.parsed_data['io_signature']

        # make
        try:
            self.parsed_data['make'] = {}
            self.parsed_data['make']['arguments'] = []
            query_m = declarations.custom_matcher_t(
                lambda mem_fun: mem_fun.name.startswith('make'))
            query_make = query_m & declarations.access_type_matcher_t('public')
            make_func = main_class.member_functions(function=query_make,
                                                    allow_empty=True,
                                                    header_file=self.target_file)
            criteria = declarations.calldef_matcher(name='make')
            _make_fun = declarations.matcher.get_single(criteria, main_class)
            _make_fun = str(_make_fun).split(
                'make')[-1].split(')')[0].split('(')[1].lstrip().rstrip().split(',')
            if make_func:
                for arg in make_func[0].arguments:
                    for _arg in _make_fun:
                        if str(arg.name) in _arg:
                            make_arguments = {
                                "name": str(arg.name),
                                "dtype": str(arg.decl_type),
                                "default": ""
                            }
                            if re.findall(r'[-+]?\d*\.\d+|\d+', _arg):
                                make_arguments['default'] = re.findall(
                                    r'[-+]?\d*\.\d+|\d+', _arg)[0]
                            elif re.findall(r'\"(.+?)\"', _arg):
                                make_arguments['default'] = re.findall(
                                    r'\"(.+?)\"', _arg)[0]
                            elif "true" in _arg:
                                make_arguments['default'] = "True"
                            elif "false" in _arg:
                                make_arguments['default'] = "False"
                    self.parsed_data['make']['arguments'].append(
                        make_arguments.copy())
        except RuntimeError:
            self.parsed_data['make'] = {}
            self.parsed_data['make']['arguments'] = []

        # setters
        try:
            self.parsed_data['methods'] = []
            query_methods = declarations.access_type_matcher_t('public')
            setters = main_class.member_functions(function=query_methods,
                                                  allow_empty=True,
                                                  header_file=self.target_file)
            getter_arguments = []
            if setters:
                for setter in setters:
                    if str(setter.name).startswith('set_') and setter.arguments:
                        setter_args = {
                            "name": str(setter.name),
                            "arguments_type": []
                        }
                        for argument in setter.arguments:
                            args = {
                                "name": str(argument.name),
                                "dtype": str(argument.decl_type)
                            }
                            getter_arguments.append(args['name'])
                            setter_args['arguments_type'].append(args.copy())
                        self.parsed_data['methods'].append(setter_args.copy())
        except RuntimeError:
            self.parsed_data['methods'] = []

        # getters
        try:
            self.parsed_data['properties'] = []
            query_properties = declarations.access_type_matcher_t('public')
            getters = main_class.member_functions(function=query_properties,
                                                  allow_empty=True,
                                                  header_file=self.target_file)
            if getters:
                for getter in getters:
                    if not getter.arguments or getter.has_const:
                        getter_args = {
                            "name": str(getter.name),
                            "dtype": str(getter.return_type),
                            "read_only": True
                        }
                        if getter_args['name'] in getter_arguments:
                            getter_args["read_only"] = False
                        self.parsed_data['properties'].append(
                            getter_args.copy())
        except RuntimeError:
            self.parsed_data['properties'] = []

        # documentation
        try:
            _index = None
            header_file = codecs.open(self.target_file, 'r', 'cp932')
            self.parsed_data['docstring'] = re.compile(
                r'//.*?$|/\*.*?\*/', re.DOTALL | re.MULTILINE).findall(
                    header_file.read())[2:]
            header_file.close()
            for doc in self.parsed_data['docstring']:
                if Constants.BLOCKTOOL in doc:
                    _index = self.parsed_data['docstring'].index(doc)
            if _index is not None:
                self.parsed_data['docstring'] = self.parsed_data['docstring'][: _index]
        except:
            self.parsed_data['docstring'] = []

        return self.parsed_data
Пример #9
0
                if isinstance(ty,declarations.cpptypes.declarated_t):
                    ty = ty.declaration
                c = ty # baseTy # .declaration
                if not isInPublicScope(c):
                    print 'exclude <template>', m
                    return False
        if isInPublicScope(m):
            return True
        else:
            print 'exclude', m
            return False
    else:
        print 'exclude', m
        return False

classList = sorted(global_ns.classes(header_dir=this_module_dir_path, function = declarations.custom_matcher_t(matcherFun) & (~(declarations.access_type_matcher_t( 'private' ) | declarations.access_type_matcher_t( 'protected' )) )), key=attrgetter('name'))
enumList = sorted(global_ns.enums(header_dir=this_module_dir_path), key=attrgetter('name'))

tyNone = 0
tyPrim = 1
tyGlue = 2
tyObj  = 3

def isGlueType(ty):
    ty = declarations.type_traits.remove_reference(declarations.type_traits.remove_cv(ty)) 
    ty = declarations.type_traits.remove_cv(ty)
    baseTy = declarations.type_traits.base_type(ty)
    if  (declarations.type_traits.is_fundamental(baseTy)) | (not declarations.type_traits.is_class(ty)) | (not declarations.type_traits.is_same(baseTy,ty)):
        return False
    if baseTy.declaration.name in glueMap:
        return True
Пример #10
0
                if not isInPublicScope(c):
                    print 'exclude <template>', m
                    return False
        if isInPublicScope(m):
            return True
        else:
            print 'exclude', m
            return False
    else:
        print 'exclude', m
        return False


classList = sorted(
    global_ns.classes(header_dir=this_module_dir_path,
                      function=declarations.custom_matcher_t(matcherFun) &
                      (~(declarations.access_type_matcher_t('private')
                         | declarations.access_type_matcher_t('protected')))),
    key=attrgetter('name'))
enumList = sorted(global_ns.enums(header_dir=this_module_dir_path),
                  key=attrgetter('name'))

tyNone = 0
tyPrim = 1
tyGlue = 2
tyObj = 3


def isGlueType(ty):
    ty = declarations.type_traits.remove_reference(
        declarations.type_traits.remove_cv(ty))
Пример #11
0
                print '\nWhile Processing FILEs: \n' +  str(sources) + '\nLines: ' + str(customCodeBlock) + '\n'

    # Execute user-specified code
    try:
        for customCodeBlock in task.custom_code:
            exec customCodeBlock in locals()
    except:
        import traceback
        traceback.print_exc()
        print '\nWhile Processing FILEs: \n' +  str(sources) + '\nLines: ' + customCodeBlock + '\n'
        return 1

    # Now I protect the virtual member calls so that they behave correctly in a multi-threaded environment
    members = mb.global_ns.calldefs( (declarations.virtuality_type_matcher(declarations.VIRTUALITY_TYPES.VIRTUAL) |
                                    declarations.virtuality_type_matcher(declarations.VIRTUALITY_TYPES.PURE_VIRTUAL)) &
                                    declarations.custom_matcher_t( lambda decl: decl.ignore == False and decl.exportable ), allow_empty=True)
    if( members ):
        for member in members:
            try:
                member.add_override_precall_code('\npyplusplus::threading::gil_guard_t gil_guard( resp::sc_controller::getController().interactive );')
                if not code_repository.gil_guard.file_name in task.ext_headers:
                    task.ext_headers.append(code_repository.gil_guard.file_name)
                controller_path = os.path.join(task.srcpath, 'src', 'controller', 'controller.hpp')
                if not controller_path in task.ext_headers:
                    task.ext_headers.append(controller_path)
                if not os.path.exists(os.path.abspath(os.path.join( task.bldpath, os.path.dirname(task.outputs[0].bldpath(task.env)),  code_repository.gil_guard.file_name) )):
                    guard = open(os.path.abspath(os.path.join( task.bldpath, os.path.dirname(task.outputs[0].bldpath(task.env)),  code_repository.gil_guard.file_name) ), 'w')
                    guard.write(code_repository.gil_guard.code)
                    guard.close()
            except AttributeError:
                pass