Update of /cvsroot/pygccxml/source/pyplusplus/experimental
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30088
Added Files:
decltypes.py declwrapper.py filters.py selection.py
Log Message:
Added an experimental replacement for the DeclWrapper/MultiDeclWrapper classes. Note: To try this out, you have to activate the new class explicitly!
--- NEW FILE: declwrapper.py ---
# Copyright 2006 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#
# Initial author: Matthias Baas
"""This module contains the 'Declaration wrapper' object.
"""
import types
from filters import *
import decltypes
import pygccxml
import pyplusplus
import selection
# Create an alias for the builtin type() function
_type = type
allow_empty_queries = False
# IDecl
class IDecl:
"""Declaration interface.
This class represents the interface to the declaration tree. Its
main purpose is to "decorate" the nodes in the tree with
information about how the binding is to be created. Instances of
this class are never created by the user, instead they are
returned by the API.
You can think of this class as a container for declaration nodes
that are selected by matching a set of filters.
@group Selection interface: Decl, Namespace, Class, Constructor, Method, Function, Enum, Var, Decls, Namespaces, Classes, Constructors, Methods, Functions, Enums, Vars
@group Decoration interface: expose, ignore, exclude, finalize, rename, setPolicy, disableKeywordArgs, setHeldType, addMethod, cdef, staticmethod
"""
def __init__(self, decls):
"""Constructor.
@param decls: One or more declarations that should be stored in this instance
@type decls: declaration_t or list of declaration_t
"""
if type(decls)!=list:
decls = [decls]
# A sequence containing the underlying pygccxml declaration nodes.
# (actually these are decl_wrapper nodes)
self.decl_handles = decls
def __str__(self):
"""Return a descriptive string."""
if len(self.decl_handles)==0:
return "Decl: <empty>"
elif len(self.decl_handles)==1:
ds = getattr(self.decl_handles[0], "name", "?")
return 'Decl: "%s"'%(ds)
else:
return 'Decl: (%d declarations)'%(len(self.decl_handles))
def __iter__(self):
return self.iterContained()
# iterContained
def iterContained(self):
"""Iterate over all contained nodes.
The iterator yields Decl objects.
"""
for decl in self._iterContained():
yield IDecl([decl])
# expose
def expose(self, flag=True):
"""Expose the declarations in the generated module.
If flag is True all contained declarations are marked
for being exposed, otherwise they are marked for being ignored.
@param flag: Determines whether the declaration is actually exposed or ignored.
@type flag: bool
@returns: Returns self
@see: L{ignore()}
"""
for d in self._iterContained():
d.include()
return self
# ignore
def ignore(self, flag=True):
"""Ignore the declarations in the generated module.
If flag is True all contained declarations are marked
for being ignored, otherwise they are marked for being exposed.
@param flag: Determines whether the declaration is actually ignored or exposed.
@type flag: bool
@return: Returns self
@see: L{expose()}
"""
for d in self._iterContained():
d.exclude()
return self
# exclude
def exclude(self, flag=True):
"""This is an alias for L{ignore()}."""
return self.ignore(flag)
# rename
def rename(self, name):
"""Rename a declaration.
The declaration will receive a new name under which it is exposed
in the Python module.
If there are currently several declarations referenced the new
name is assigned to all of them. However, only the declarations
that were directly matched will receive a new name, children are
always ignored.
@param name: New name for the declaration
@type name: str
"""
for decl in self._iterContained(recursive=False):
decl.rename(name)
return self
# finalize
def finalize(self):
"""Finalize virtual member functions or an entire class.
Prevents the generation of wrappers for virtual member functions.
"""
for decl in self._iterContained():
decl.finalize()
return self
# setPolicy
def setPolicy(self, policy):
"""Set policies for functions or methods.
@param policy: Policy to apply to the contained functions/methods.
@type policy: ...policy...
"""
for decl in self._iterContained():
decl.call_policies = policy
# setHeldType
def setHeldType(self, heldtype):
"""Explicitly set the held type.
Ex: C{setHeldType("boost::shared_ptr<Class>")}
"""
for decl in self._iterContained():
decl.held_type = heldType
return self
# disableKeywordArgs
def disableKeywordArgs(self):
"""Disable generation of keyword arguments.
"""
for decl in self._iterContained():
decl.use_keywords = False
# if ( isinstance(decl, calldef_t) and
# not isinstance(decl, destructor_t) and
# getattr(decl, "access_type", None)!=PRIVATE):
# decl._use_keywords = False
return self
# addMethod
def addMethod(self, name, impl):
"""Add a new method to a class.
Adds a new method to a class. The implementation is given as a
C/C++ function that is defined elsewhere.
The return value is a Decl object that can be
used to further customize the method.
@Note: This method isn't implemented yet!
@param name: The method name as it will appear in the Python module
@type name: str:
@param impl: The name of the C/C++ function that implements the method.
@type impl: str
@returns: Returns a Decl object containing the newly created method.
"""
raise NotImplementedError, "addMethod() isn't implemented yet"
pass
# def
def cdef(self, name, fn, *args):
"""Apply a raw def() statement.
This method is equivalent to the Boost.Python def() method.
Example::
Class("Foo").cdef("spam", "cspam", return_internal_reference(), (arg("a"), arg("b", 0)), "The spam method")
It is up to the user to ensure that the C/C++ function cspam
is declared and implemented somewhere.
@param name: Name of the Python method
@type name: str
@param fn: Name of the C++ function that implements the method
@type fn: str
@param args: There can be up to three additional arguments in any order: A doc string, the call policies and the keywords.
@see: L{staticmethod()}
"""
raise NotImplementedError, "cdef() isn't implemented yet"
## doc,policies,keywords = self._parseDefArgs(args)
## args = ['"%s"'%name, fn]
## if policies!=None:
## pass # todo
## if keywords!=None:
## args.append("(%s)"%", ".join(map(lambda x: "bp::"+str(x), keywords)))
## if doc!=None:
## a = map(lambda x: "%s\\n"%x, doc.split("\n"))
## while len(a)>0 and a[-1]=="\\n":
## a = a[:-1]
## if len(a)>0:
## # Remove the newline in the last line
## a[-1] = a[-1][:-2]
## args.append('%s'%"\n".join(map(lambda x: '"%s"'%x, a)))
## src = 'def( %s )'%(", ".join(args))
## for decl in self._iterContained(no_children=True):
## # Add the 'def' source code line to the list of defs...
## if not hasattr(decl, "_user_defs"):
## decl._user_defs = []
## decl._user_defs.append(src)
return self
# staticmethod
def staticmethod(self, name):
"""Apply a raw staticmethod() statement.
@param name: Name of the method.
@type name: str
@see: L{cdef()}
"""
raise NotImplementedError, "staticmethod() isn't implemented yet"
# for decl in self._iterContained(no_children=True):
# if not hasattr(decl, "_user_defs"):
# decl._user_defs = []
# decl._user_defs.append('staticmethod( "%s" )'%name)
return self
# Decl
def Decls(self,
name=None,
fullname=None,
type=None,
retval=None,
args=None,
anyarg=None,
signature=None,
header=None,
headerdir=None,
accesstype=None,
filter=None,
include_children=True,
assert_count=None
):
"""Obtain a Decl object referencing one or more declarations.
Filters all contained declarations and returns a new Decl
object that only contains declarations matching the filtering
rules as specified by the arguments. If an argument is None,
that particular filtering operation is disabled. If several
arguments are provided, all of them must be matched.
For any filter that is based on strings (such as name) the
following rules apply:
- A string must match exactly the corresponding attribute of the
declaration (C{name="wxFrame"} will only return the class
"wxFrame").
- A string that is bracketed by a leading and trailing slash '/' is
interpreted as a regular expression (C{name="/wx.*/"} will return
all classes that begin with "wx").
Any argument can also be passed a list of values which duplicates
the filter. These filter are concatenated with OR, so a declaration
has to match only one of the filters. For example, you can select all
classes starting with either "wx" or "WX" by setting
C{name=["/wx.*/", "/WX.*/"}].
The user defined filter function filter must accept a Decl
object as argument and has to return True when the declaration
is matched.
@param name: Select declarations by name
@type name: str
@param fullname: Select declarations by name (which includes namespaces)
@type fullname: str
@param type: Select declarations by type. The type is given by a combination of flags (CLASS, MEMBER_FUNCTION/METHOD, FREE_FUNCTION/FUNCTION, ENUM, ...)
@type type: int
@param retval: Select functions/methods based on their return value (this implies the type flags MEMBER_FUNCTION | FREE_FUNCTION)
@type retval: str
@param args: Select functions/methods bases on their arguments (this implies the type flags MEMBER_FUNCTION | FREE_FUNCTION)
@type args: list of str
@param anyarg: Select all functions/methods that have the specified argument somewhere in their argument list (this implies the type flags MEMBER_FUNCTION | FREE_FUNCTION)
@type anyarg: str
@param signature: Select declarations by their signature (this implies the type flags MEMBER_FUNCTION | FREE_FUNCTION)
@type signature: str
@param header: Select declarations by the header file in which they are defined
@type header: str
@param headerdir: Select declarations by the directory in which their header file is located
@type headerdir: str
@param accesstype: Access type (PUBLIC or PROTECTED). This implies the type flag MEMBER_FUNCTION.
@param filter: User defined filter function
@type callable
@param assert_count: Check the number of matched declarations in the resulting Decl object
@type assert_count: int
@returns: Returns a Decl object that may reference an arbitrary number of declarations.
@see: Namespace(), Class(), Method(), Function(), Enum()
"""
itype = 0
filters = []
def addFilter(arg, filtercls):
if arg!=None:
if _type(arg)==list:
filters.append(OrFilter(map(lambda x: filtercls(x), arg)))
else:
filters.append(filtercls(arg))
# name filter
addFilter(name, NameFilter)
# fullname filter
addFilter(fullname, FullNameFilter)
# retval filter
if retval!=None:
addFilter(retval, RetValFilter)
itype |= CALLABLE
# args filter
if args!=None:
filters.append([ArgsFilter(args)])
type |= CALLABLE
# anyarg filter
if anyarg!=None:
raise NotImplementedError, "anyarg filter is not yet implemented"
# signature filter
if signature!=None:
raise NotImplementedError, "signature filter is not yet implemented"
# header filter
addFilter(header, HeaderFilter)
# headerdir filter
addFilter(headerdir, HeaderDirFilter)
# accesstype filter
if accesstype!=None:
addFilter(accesstype, AccessTypeFilter)
type |= METHOD
# custom filters
if filter!=None:
if _type(filter)==list:
filters.extend(filter)
else:
filters.append(filter)
# XXX
if itype!=0:
if type==None:
type = 0
type |= itype
addFilter(type, TypeFilter)
if len(filters)==0:
filter = TrueFilter()
elif len(filters)==1:
filter = filters[0]
else:
filter = AndFilter(filters)
# print "Filter:",filter
if len(self.decl_handles)!=1:
print "***WARNING***: len(decl_handles) != 1"
root = self.decl_handles[0]
decls = selection.select(root, filter)
res = IDecl(decls)
count = res.count
if allow_empty_queries and count==0:
return res
if count==0:
raise RuntimeError, "Query produced no results (filter: %s)"%filter
if assert_count!=None:
if res.count!=assert_count:
raise RuntimeError, "Query produced the wrong number of results (%d instead of %d)"%(res.count, assert_count)
return res
# Namespace
def Namespaces(self, name=None, type=0, **args):
"""Obtain a Decl object referencing one or more namespaces.
This method is equivalent to calling Decl() with the flag NAMESPACE
set in its type filter.
See Decl() for a full description of this method.
@returns: Returns a Decl object that may reference an arbitrary number of declarations.
@see: L{Decl()}
"""
return self.Decls(name=name, type=type|NAMESPACE, **args)
# Class
def Classes(self, name=None, type=0, **args):
return self.Decls(name=name, type=type|CLASS, **args)
# Method
def Methods(self, name=None, type=0, **args):
return self.Decls(name=name, type=type|METHOD, **args)
# Constructor
def Constructors(self, name=None, type=0, **args):
return self.Decls(name=name, type=type|CONSTRUCTOR, **args)
# Function
def Functions(self, name=None, type=0, **args):
return self.Decls(name=name, type=type|FUNCTION, **args)
# Enum
def Enums(self, name=None, type=0, **args):
return self.Decls(name=name, type=type|ENUM, **args)
# Vars
def Vars(self, name=None, type=0, **args):
return self.Vars(name=name, type=type|VARIABLE, **args)
# Decl
def Decl(self, name=None, **args):
return self.Decls(name, assert_count=1, **args)
# Namespace
def Namespace(self, name=None, **args):
return self.Namespaces(name, assert_count=1, **args)
# Class
def Class(self, name=None, **args):
return self.Classes(name, assert_count=1, **args)
# Method
def Method(self, name=None, **args):
return self.Methods(name, assert_count=1, **args)
# Constructor
def Constructor(self, name=None, **args):
return self.Constructors(name, assert_count=1, **args)
# Function
def Function(self, name=None, **args):
return self.Functions(name, assert_count=1, **args)
# Enum
def Enum(self, name=None, **args):
return self.Enums(name, assert_count=1, **args)
# Var
def Var(self, name=None, **args):
return self.Vars(name, assert_count=1, **args)
# Private methods:
def _getCount(self):
"""Return the number of matched declarations.
"""
return len(self.decl_handles)
count = property(_getCount, None, None, "The number of matched declarations.")
def _getTotalCount(self):
"""Return the total number of contained declarations (including the children).
"""
return len(list(self))
totalcount = property(_getTotalCount, None, None, "The total number of contained declarations.")
def _parseDefArgs(self, args):
"""Determine which of the args is the doc string, call policies and keywords argument.
@returns: Returns a tuple (doc, policies, keywords).
"""
if len(args)>3:
raise ValueError, "Too many arguments (%d)"%len(args)
doc = None
policies = None
keywords = None
# call_policy_t = pyplusplus.code_creators.call_policies.call_policy_t
call_policy_t = pyplusplus.decl_wrappers.call_policies.call_policy_t
for a in args:
if isinstance(a, types.StringTypes):
doc = a
elif isinstance(a, call_policy_t):
policies = a
elif type(a)==tuple:
keywords = a
elif isinstance(a, decltypes.arg):
keywords = (a,)
else:
raise ValueError, "Invalid argument: %s"%a
return doc,policies,keywords
def _iterContained(self, recursive=True):
"""Iterate over all contained declarations.
The generator yields pygccxml declaration objects.
@param recursive: Determines whether the method also yields children nodes
@type recursive: bool
"""
global _timestamp
_timestamp += 1
for rootdecl in self.decl_handles:
for decl in self._iterdecls(rootdecl, recursive=recursive):
# Get the time stamp and check if this declaration hasn't
# been visited yet
ts = getattr(decl, "_timestamp", -1)
if ts!=_timestamp:
decl._timestamp = _timestamp
yield decl
# _iterdecls
def _iterdecls(self, rootdecl, recursive=True):
"""Depth first iteration over one or more declaration trees.
rootdecl can be either a single declaration, a list of
declarations or None. A declaration must be an object derived
from the declaration_t class. If recursive is False, only the
root is returned.
@param recursive: Determines whether the method also yields children nodes
@type recursive: bool
"""
if rootdecl==None:
return
if type(rootdecl) is not list:
rootdecl = [rootdecl]
for root in rootdecl:
yield root
if recursive:
children = getattr(root, "declarations", None)
for node in self._iterdecls(children):
yield node
# This value is used to determine if a declaration was already visited or not
_timestamp = 0
--- NEW FILE: decltypes.py ---
# Copyright 2006 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#
# Initial author: Matthias Baas
"""This module contains some basic definitions.
"""
NAMESPACE = 0x01
CLASS = 0x02
MEMBER_FUNCTION = 0x04
METHOD = MEMBER_FUNCTION # this also includes constructors
FREE_FUNCTION = 0x08
FUNCTION = FREE_FUNCTION
CONSTRUCTOR = 0x10 # limit to constructors
ENUM = 0x20
VARIABLE = 0x40
CALLABLE = METHOD | FUNCTION | CONSTRUCTOR
# arg
class arg:
"""Provide keyword arguments for methods/functions.
This class is equivalent to the Boost.Python arg class
and is used together with the Decl.cdef method.
"""
def __init__(self, name, default=None):
"""Constructor.
@param name: Argument name
@type name: str
@param default: Optional default value
"""
self.name = name
self.default = default
def __str__(self):
res = 'arg("%s")'%self.name
if self.default!=None:
res += "=%s"%self.py2cpp(self.default)
return res
def py2cpp(self, val):
"""Convert a Python value to a C++ value.
"""
if type(val)==bool:
return str(val).lower()
elif type(val)==str:
return '"%s"'%val
else:
return str(val)
--- NEW FILE: selection.py ---
# Copyright 2006 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#
# Initial author: Matthias Baas
"""This module contains the generic selection function.
"""
# iterdecls
def iterdecls(rootdecl, recursive=True):
"""Depth first iteration over one or more declaration trees.
rootdecl can be either a single declaration, a list of declarations
or None. A declaration must be an object derived from the declaration_t
class.
"""
if rootdecl==None:
return
if type(rootdecl) is not list:
rootdecl = [rootdecl]
for root in rootdecl:
yield root
if recursive:
children = getattr(root, "declarations", None)
for node in iterdecls(children):
yield node
# select
def select(root, filter):
"""Select declarations based on a filter function.
filter must to accept a declaration as argument and return a boolean
indicating whether the declarations matches the filter or not.
@param root: Root of the declaration tree
@type root: declaration_t
@param filter: A filter that either accepts or rejects a declaration
@type filter: callable
"""
parents = None
# First check for the parentConstraints() method so that also
# regular functions can be passed
if hasattr(filter, "parentConstraints"):
parents = filter.parentConstraints()
# Does the filter always return False?
if parents==[]:
return []
# No constraints on the parent? Then use the root and walk the entire tree
if parents==None:
parents = [(root, True)]
res = []
for parent,recursive in parents:
for decl in iterdecls(parent):
if filter(decl):
res.append(decl)
return res
--- NEW FILE: filters.py ---
# Copyright 2006 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#
# Initial author: Matthias Baas
"""This module contains the filters that are used to select declarations.
"""
import re, os.path
from pygccxml.declarations import *
from decltypes import *
# _StringMatcher
class _StringMatcher:
"""Helper class to match strings.
This class can be used to match a string with a pattern that may
either be an ordinary string as well or contain a regular expression
enclosed in '/'.
"""
def __init__(self, pattern):
"""Constructor.
pattern may contain a regular expression enclosed between two '/'.
@param pattern: The pattern used for matching
@type pattern: str
"""
self.regexp = None
self.pattern = pattern
# Is pattern a regular expression?
if len(pattern)>=2 and pattern[0]=="/" and pattern[-1]=="/":
self.regexp = re.compile(pattern[1:-1])
# match
def match(self, txt):
"""Check if a string matches the pattern.
@param txt: The string to match
@type txt: str
@returns: True if txt matches the pattern
"""
if self.regexp==None:
return txt==self.pattern
else:
m = self.regexp.match(txt)
if m==None:
return False
# It was only a successful match when the entire string was matched
return m.end()==len(txt)
# FilterBase
class FilterBase:
"""Base class for all filters.
"""
def __init__(self):
pass
def __call__(self, decl):
raise NotImplementedError, "filters must always implement the __call__() method."
def __invert__(self):
"""NOT-operator (~)"""
return NotFilter(self)
def __and__(self, other):
"""AND-operator (&)"""
return AndFilter([self, other])
def __or__(self, other):
"""OR-Operator (|)"""
return OrFilter([self, other])
def parentConstraints(self):
"""Return the parent constraints.
@returns: Tuple (parent, recursive)
"""
return None
# TrueFilter
class TrueFilter(FilterBase):
"""Returns always True.
"""
def __call__(self, decl):
return True
def __str__(self):
return "True"
# FalseFilter
class FalseFilter(FilterBase):
"""Returns always False.
"""
def __call__(self, decl):
return False
def __str__(self):
return "False"
# AndFilter
class AndFilter(FilterBase):
"""Combine several other filters with AND.
"""
def __init__(self, filters):
FilterBase.__init__(self)
self.filters = filters
def __str__(self):
return " & ".join(map(lambda x: "(%s)"%str(x), self.filters))
def __call__(self, decl):
for f in self.filters:
if not f(decl):
return False
return True
def parentConstraints(self):
parent = None
recursive = None
for f in self.filters:
res = f.parentConstraints()
# No constraints? Then go on with the next filter...
if res==None:
continue
# One individual filter always fails?
# Then this filter fails as well...
if res==[]:
return []
# Check if the individual constraints are conflicting...
for p,r in res:
if parent==None:
parent = p
recursive = r
else:
if p==parent:
# recursive only remains True if r is also True
recursive = recursive & r
else:
# Two different parents => This filter will always fail
return []
if parent==None:
return None
else:
return [parent, recursive]
# OrFilter
class OrFilter(FilterBase):
"""Combine several other filters with OR.
"""
def __init__(self, filters):
FilterBase.__init__(self)
self.filters = filters
def __str__(self):
return " | ".join(map(lambda x: "(%s)"%str(x), self.filters))
def __call__(self, decl):
for f in self.filters:
if f(decl):
return True
return False
def parentConstraints(self):
remove = []
constraints = []
for f in self.filters:
res = f.parentConstraints()
if res==[]:
remove.append(f)
continue
if res!=None:
constraints.extend(res)
# Remove all filters that always return False
for f in remove:
self.filters.remove(f)
if constraints==[]:
return None
else:
return constraints
# NotFilter
class NotFilter(FilterBase):
"""Return the inverse result of a filter.
"""
def __init__(self, filter):
FilterBase.__init__(self)
self.filter = filter
def __str__(self):
return "~(%s)"%str(self.filter)
def __call__(self, decl):
return not self.filter(decl)
# NameFilter
class NameFilter(FilterBase):
"""Filter by declaration name.
"""
def __init__(self, namepattern):
FilterBase.__init__(self)
self.matcher = _StringMatcher(namepattern)
def __str__(self):
return "name=='%s'"%self.matcher.pattern
def __call__(self, decl):
return self.matcher.match(decl.name)
# FullNameFilter
class FullNameFilter(FilterBase):
"""Filter by full declaration name.
"""
def __init__(self, namepattern):
FilterBase.__init__(self)
self.matcher = _StringMatcher(namepattern)
def __str__(self):
return "fullname=='%s'"%self.matcher.pattern
def __call__(self, decl):
return self.matcher.match(full_name(decl))
# RetValFilter
class RetValFilter(FilterBase):
"""Filter by return type.
"""
def __init__(self, retval):
FilterBase.__init__(self)
self.retval = retval
def __str__(self):
return "retval==%s"%self.retval
def __call__(self, decl):
rettype = getattr(decl, "return_type", None)
if rettype==None:
return False
return rettype.decl_string==self.retval
# ArgsFilter
class ArgsFilter(FilterBase):
"""Filter by argument types.
"""
def __init__(self, args):
FilterBase.__init__(self)
self.args = args
def __str__(self):
return "args==%s"%self.args
def __call__(self, decl):
args = self.args
declargs = getattr(decl, "arguments", None)
if declargs==None:
return False
if len(args)!=len(declargs):
return False
for arg,argument in zip(args, declargs):
if arg!=argument.type.decl_string:
return False
return True
# TypeFilter
class TypeFilter(FilterBase):
"""Filter by declaration type.
"""
def __init__(self, typeflags):
FilterBase.__init__(self)
self.flags = typeflags
def __str__(self):
f = self.flags
t = []
if f & NAMESPACE:
t.append("NAMESPACE")
if f & CLASS:
t.append("CLASS")
if f & METHOD:
t.append("METHOD")
if f & FUNCTION:
t.append("FUNCTION")
if f & CONSTRUCTOR:
t.append("CONSTRUCTOR")
if f & ENUM:
t.append("ENUM")
return "type==%s"%("|".join(t))
def __call__(self, decl):
return (self.declFlags(decl) & self.flags)!=0
# declFlags
def declFlags(self, decl):
"""Return the type flags for decl.
@param decl: Declaration
@type decl: declaration_t
"""
res = 0
if isinstance(decl, class_t):
res |= CLASS
elif isinstance(decl, member_calldef_t):
res |= METHOD
elif isinstance(decl, free_calldef_t):
res |= FUNCTION
elif isinstance(decl, enumeration.enumeration_t):
res |= ENUM
elif isinstance(decl, namespace_t):
res |= NAMESPACE
if isinstance(decl, constructor_t):
res |= CONSTRUCTOR
return res
# HeaderFilter
class HeaderFilter(FilterBase):
"""Filter by header file.
"""
def __init__(self, header):
FilterBase.__init__(self)
self.header = os.path.abspath(header)
def __str__(self):
return "header==%s"%self.header
def __call__(self, decl):
loc = getattr(decl, "location", None)
if loc==None:
return False
header = os.path.abspath(loc.file_name)
return header==self.header
# HeaderDirFilter
class HeaderDirFilter(FilterBase):
"""Filter by header location.
"""
def __init__(self, headerdir):
FilterBase.__init__(self)
self.headerdir = os.path.abspath(headerdir)
def __str__(self):
return "headerdir==%s"%self.headerdir
def __call__(self, decl):
loc = getattr(decl, "location", None)
if loc==None:
return False
dir = os.path.abspath(os.path.dirname(loc.file_name))
return dir[:len(self.headerdir)]==self.headerdir
# AccessTypeFilter
class AccessTypeFilter(FilterBase):
"""Filter by access type.
"""
def __init__(self, accesstype):
"""Constructor.
accesstype can bei either PUBLIC or PROTECTED.
"""
FilterBase.__init__(self)
self.accesstype = accesstype
def __str__(self):
return "accesstype==%s"%self.accesstype
def __call__(self, decl):
at = getattr(decl, "access_type", None)
if at==None:
return False
return at==self.accesstype
|