Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_34_1/libs/python/pyste/src/Pyste/declarations.py @ 29

Last change on this file since 29 was 29, checked in by landauf, 17 years ago

updated boost from 1_33_1 to 1_34_1

File size: 20.9 KB
Line 
1# Copyright Bruno da Silva de Oliveira 2003. Use, modification and
2# distribution is subject to the Boost Software License, Version 1.0.
3# (See accompanying file LICENSE_1_0.txt or copy at
4# http:#www.boost.org/LICENSE_1_0.txt)
5
6'''
7Defines classes that represent declarations found in C++ header files.
8   
9'''
10
11# version indicates the version of the declarations. Whenever a declaration
12# changes, this variable should be updated, so that the caches can be rebuilt
13# automatically
14version = '1.0'
15
16#==============================================================================
17# Declaration
18#==============================================================================
19class Declaration(object):
20    '''Base class for all declarations.
21    @ivar name: The name of the declaration.
22    @ivar namespace: The namespace of the declaration.
23    '''
24
25    def __init__(self, name, namespace):
26        '''
27        @type name: string
28        @param name: The name of this declaration
29        @type namespace: string
30        @param namespace: the full namespace where this declaration resides.
31        '''
32        self.name = name
33        self.namespace = namespace
34        self.location = '', -1  # (filename, line)
35        self.incomplete = False
36        self.is_unique = True
37
38
39    def FullName(self):
40        '''
41        Returns the full qualified name: "boost::inner::Test"
42        @rtype: string
43        @return: The full name of the declaration.
44        '''
45        namespace = self.namespace or ''
46        if namespace and not namespace.endswith('::'):
47            namespace += '::'
48        return namespace + self.name
49   
50   
51    def __repr__(self):       
52        return '<Declaration %s at %s>' % (self.FullName(), id(self))
53
54
55    def __str__(self):
56        return 'Declaration of %s' % self.FullName()
57   
58   
59#==============================================================================
60# Class
61#==============================================================================
62class Class(Declaration):
63    '''
64    Represents a C++ class or struct. Iteration through it yields its members.
65
66    @type abstract: bool
67    @ivar abstract: if the class has any abstract methods.
68
69    @type bases: tuple
70    @ivar bases: tuple with L{Base} instances, representing the most direct
71    inheritance.
72
73    @type hierarchy: list
74    @ivar hierarchy: a list of tuples of L{Base} instances, representing
75    the entire hierarchy tree of this object. The first tuple is the parent
76    classes, and the other ones go up in the hierarchy.
77    '''
78
79    def __init__(self, name, namespace, members, abstract):
80        Declaration.__init__(self, name, namespace)
81        self.__members = members
82        self.__member_names = {}
83        self.abstract = abstract
84        self.bases = ()
85        self.hierarchy = ()
86        self.operator = {}
87
88
89    def __iter__(self):
90        '''iterates through the class' members.
91        '''
92        return iter(self.__members)           
93
94
95    def Constructors(self, publics_only=True):
96        '''Returns a list of the constructors for this class.
97        @rtype: list
98        '''
99        constructors = []
100        for member in self:
101            if isinstance(member, Constructor):
102                if publics_only and member.visibility != Scope.public:
103                    continue
104                constructors.append(member)
105        return constructors
106
107   
108    def HasCopyConstructor(self):
109        '''Returns true if this class has a public copy constructor.
110        @rtype: bool
111        '''
112        for cons in self.Constructors():
113            if cons.IsCopy():
114                return True
115        return False
116
117
118    def HasDefaultConstructor(self):
119        '''Returns true if this class has a public default constructor.
120        @rtype: bool
121        '''
122        for cons in self.Constructors():
123            if cons.IsDefault():
124                return True
125        return False
126
127
128    def AddMember(self, member):
129        if member.name in self.__member_names:
130            member.is_unique = False
131            for m in self:
132                if m.name == member.name:
133                    m.is_unique = False
134        else:
135            member.is_unique = True
136        self.__member_names[member.name] = 1
137        self.__members.append(member)
138        if isinstance(member, ClassOperator):
139            self.operator[member.name] = member
140
141
142    def ValidMemberTypes():
143        return (NestedClass, Method, Constructor, Destructor, ClassVariable, 
144                ClassOperator, ConverterOperator, ClassEnumeration)   
145    ValidMemberTypes = staticmethod(ValidMemberTypes)
146
147                         
148#==============================================================================
149# NestedClass
150#==============================================================================
151class NestedClass(Class):
152    '''The declaration of a class/struct inside another class/struct.
153   
154    @type class: string
155    @ivar class: fullname of the class where this class is contained.
156
157    @type visibility: L{Scope}
158    @ivar visibility: the visibility of this class.
159    '''
160
161    def __init__(self, name, class_, visib, members, abstract):
162        Class.__init__(self, name, None, members, abstract)
163        self.class_ = class_
164        self.visibility = visib
165
166
167    def FullName(self):
168        '''The full name of this class, like ns::outer::inner.
169        @rtype: string
170        '''
171        return '%s::%s' % (self.class_, self.name)
172   
173
174#==============================================================================
175# Scope   
176#==============================================================================
177class Scope:   
178    '''Used to represent the visibility of various members inside a class.
179    @cvar public: public visibility
180    @cvar private: private visibility
181    @cvar protected: protected visibility
182    '''
183    public = 'public'
184    private = 'private'
185    protected = 'protected'
186   
187 
188#==============================================================================
189# Base   
190#==============================================================================
191class Base:
192    '''Represents a base class of another class.
193    @ivar _name: the full name of the base class.
194    @ivar _visibility: the visibility of the derivation.
195    '''
196
197    def __init__(self, name, visibility=Scope.public):
198        self.name = name
199        self.visibility = visibility
200
201   
202#==============================================================================
203# Function   
204#==============================================================================
205class Function(Declaration):
206    '''The declaration of a function.
207    @ivar _result: instance of L{Type} or None.
208    @ivar _parameters: list of L{Type} instances.
209    @ivar _throws: exception specifiers or None
210    '''
211
212    def __init__(self, name, namespace, result, params, throws=None): 
213        Declaration.__init__(self, name, namespace)
214        # the result type: instance of Type, or None (constructors)           
215        self.result = result
216        # the parameters: instances of Type
217        self.parameters = params
218        # the exception specification
219        self.throws     = throws
220
221
222    def Exceptions(self):
223        if self.throws is None:
224            return ""
225        else:
226            return " throw(%s)" % ', '.join ([x.FullName() for x in self.throws]) 
227
228
229    def PointerDeclaration(self, force=False):
230        '''Returns a declaration of a pointer to this function.
231        @param force: If True, returns a complete pointer declaration regardless
232        if this function is unique or not.
233        '''
234        if self.is_unique and not force:
235            return '&%s' % self.FullName()
236        else:
237            result = self.result.FullName()
238            params = ', '.join([x.FullName() for x in self.parameters]) 
239            return '(%s (*)(%s)%s)&%s' % (result, params, self.Exceptions(), self.FullName())
240
241   
242    def MinArgs(self):
243        min = 0
244        for arg in self.parameters:
245            if arg.default is None:
246                min += 1
247        return min
248
249    minArgs = property(MinArgs)
250   
251
252    def MaxArgs(self):
253        return len(self.parameters)
254
255    maxArgs = property(MaxArgs)
256
257   
258   
259#==============================================================================
260# Operator
261#==============================================================================
262class Operator(Function):
263    '''The declaration of a custom operator. Its name is the same as the
264    operator name in C++, ie, the name of the declaration "operator+(..)" is
265    "+".
266    '''
267   
268    def FullName(self):
269        namespace = self.namespace or ''
270        if not namespace.endswith('::'):
271            namespace += '::'
272        return namespace + 'operator' + self.name
273
274
275#==============================================================================
276# Method
277#==============================================================================
278class Method(Function):
279    '''The declaration of a method.
280   
281    @ivar _visibility: the visibility of this method.
282    @ivar _virtual: if this method is declared as virtual.
283    @ivar _abstract: if this method is virtual but has no default implementation.
284    @ivar _static: if this method is static.
285    @ivar _class: the full name of the class where this method was declared.
286    @ivar _const: if this method is declared as const.
287    @ivar _throws: list of exception specificiers or None
288    '''
289
290    def __init__(self, name, class_, result, params, visib, virtual, abstract, static, const, throws=None): 
291        Function.__init__(self, name, None, result, params, throws)
292        self.visibility = visib
293        self.virtual = virtual
294        self.abstract = abstract
295        self.static = static
296        self.class_ = class_
297        self.const = const
298
299   
300    def FullName(self):
301        return self.class_ + '::' + self.name
302
303
304    def PointerDeclaration(self, force=False):
305        '''Returns a declaration of a pointer to this member function.
306        @param force: If True, returns a complete pointer declaration regardless
307        if this function is unique or not.
308        '''
309        if self.static:
310            # static methods are like normal functions
311            return Function.PointerDeclaration(self, force)
312        if self.is_unique and not force:
313            return '&%s' % self.FullName()
314        else:
315            result = self.result.FullName()
316            params = ', '.join([x.FullName() for x in self.parameters]) 
317            const = ''
318            if self.const:
319                const = 'const'           
320            return '(%s (%s::*)(%s) %s%s)&%s' %\
321                (result, self.class_, params, const, self.Exceptions(), self.FullName()) 
322
323
324#==============================================================================
325# Constructor
326#==============================================================================
327class Constructor(Method):
328    '''A class' constructor.
329    '''
330
331    def __init__(self, name, class_, params, visib):
332        Method.__init__(self, name, class_, None, params, visib, False, False, False, False)
333
334
335    def IsDefault(self):
336        '''Returns True if this constructor is a default constructor.
337        '''
338        return len(self.parameters) == 0 and self.visibility == Scope.public
339
340
341    def IsCopy(self):
342        '''Returns True if this constructor is a copy constructor.
343        '''
344        if len(self.parameters) != 1:
345            return False
346        param = self.parameters[0]
347        class_as_param = self.parameters[0].name == self.class_
348        param_reference = isinstance(param, ReferenceType) 
349        is_public = self.visibility == Scope.public
350        return param_reference and class_as_param and param.const and is_public
351       
352
353    def PointerDeclaration(self, force=False):
354        return ''
355
356
357#==============================================================================
358# Destructor
359#==============================================================================
360class Destructor(Method):
361    'The destructor of a class.'
362
363    def __init__(self, name, class_, visib, virtual):
364        Method.__init__(self, name, class_, None, [], visib, virtual, False, False, False)
365
366    def FullName(self):
367        return self.class_ + '::~' + self.name
368
369
370    def PointerDeclaration(self, force=False):
371        return ''
372
373
374
375#==============================================================================
376# ClassOperator
377#==============================================================================
378class ClassOperator(Method):
379    'A custom operator in a class.'
380   
381    def FullName(self):
382        return self.class_ + '::operator ' + self.name
383
384
385
386#==============================================================================
387# ConverterOperator
388#==============================================================================
389class ConverterOperator(ClassOperator):
390    'An operator in the form "operator OtherClass()".'
391   
392    def FullName(self):
393        return self.class_ + '::operator ' + self.result.FullName()
394
395   
396
397#==============================================================================
398# Type
399#==============================================================================
400class Type(Declaration):
401    '''Represents the type of a variable or parameter.
402    @ivar _const: if the type is constant.
403    @ivar _default: if this type has a default value associated with it.
404    @ivar _volatile: if this type was declared with the keyword volatile.
405    @ivar _restricted: if this type was declared with the keyword restricted.
406    @ivar _suffix: Suffix to get the full type name. '*' for pointers, for
407    example.
408    '''
409
410    def __init__(self, name, const=False, default=None, suffix=''):
411        Declaration.__init__(self, name, None)
412        # whatever the type is constant or not
413        self.const = const
414        # used when the Type is a function argument
415        self.default = default
416        self.volatile = False
417        self.restricted = False
418        self.suffix = suffix
419
420    def __repr__(self):
421        if self.const:
422            const = 'const '
423        else:
424            const = ''
425        return '<Type ' + const + self.name + '>'
426
427
428    def FullName(self):
429        if self.const:
430            const = 'const '
431        else:
432            const = ''
433        return const + self.name + self.suffix
434
435
436#==============================================================================
437# ArrayType
438#==============================================================================
439class ArrayType(Type):
440    '''Represents an array.
441    @ivar min: the lower bound of the array, usually 0. Can be None.
442    @ivar max: the upper bound of the array. Can be None.
443    '''
444
445    def __init__(self, name, const, min, max): 
446        'min and max can be None.'
447        Type.__init__(self, name, const)
448        self.min = min
449        self.max = max       
450
451
452
453#==============================================================================
454# ReferenceType   
455#==============================================================================
456class ReferenceType(Type): 
457    '''A reference type.'''
458
459    def __init__(self, name, const=False, default=None, expandRef=True, suffix=''):
460        Type.__init__(self, name, const, default)
461        if expandRef:
462            self.suffix = suffix + '&'
463       
464       
465#==============================================================================
466# PointerType
467#==============================================================================
468class PointerType(Type):
469    'A pointer type.'
470   
471    def __init__(self, name, const=False, default=None, expandPointer=False, suffix=''):
472        Type.__init__(self, name, const, default)
473        if expandPointer:
474            self.suffix = suffix + '*'
475   
476
477#==============================================================================
478# FundamentalType
479#==============================================================================
480class FundamentalType(Type): 
481    'One of the fundamental types, like int, void, etc.'
482
483    def __init__(self, name, const=False, default=None): 
484        Type.__init__(self, name, const, default)
485
486
487
488#==============================================================================
489# FunctionType
490#==============================================================================
491class FunctionType(Type):
492    '''A pointer to a function.
493    @ivar _result: the return value
494    @ivar _parameters: a list of Types, indicating the parameters of the function.
495    @ivar _name: the name of the function.
496    '''
497
498    def __init__(self, result, parameters): 
499        Type.__init__(self, '', False)
500        self.result = result
501        self.parameters = parameters
502        self.name = self.FullName()
503
504
505    def FullName(self):
506        full = '%s (*)' % self.result.FullName()
507        params = [x.FullName() for x in self.parameters]
508        full += '(%s)' % ', '.join(params)       
509        return full
510   
511   
512#==============================================================================
513# MethodType
514#==============================================================================
515class MethodType(FunctionType):
516    '''A pointer to a member function of a class.
517    @ivar _class: The fullname of the class that the method belongs to.
518    '''
519
520    def __init__(self, result, parameters, class_): 
521        self.class_ = class_
522        FunctionType.__init__(self, result, parameters)
523
524
525    def FullName(self):
526        full = '%s (%s::*)' % (self.result.FullName(), self.class_)
527        params = [x.FullName() for x in self.parameters]
528        full += '(%s)' % ', '.join(params)
529        return full
530   
531     
532#==============================================================================
533# Variable
534#==============================================================================
535class Variable(Declaration):
536    '''Represents a global variable.
537
538    @type _type: L{Type}
539    @ivar _type: The type of the variable.
540    '''
541   
542    def __init__(self, type, name, namespace):
543        Declaration.__init__(self, name, namespace)
544        self.type = type
545
546
547#==============================================================================
548# ClassVariable
549#==============================================================================
550class ClassVariable(Variable):
551    '''Represents a class variable.
552
553    @type _visibility: L{Scope}
554    @ivar _visibility: The visibility of this variable within the class.
555
556    @type _static: bool
557    @ivar _static: Indicates if the variable is static.
558
559    @ivar _class: Full name of the class that this variable belongs to.
560    '''
561
562    def __init__(self, type, name, class_, visib, static):
563        Variable.__init__(self, type, name, None)
564        self.visibility = visib
565        self.static = static
566        self.class_ = class_
567   
568
569    def FullName(self):
570        return self.class_ + '::' + self.name
571
572       
573#==============================================================================
574# Enumeration   
575#==============================================================================
576class Enumeration(Declaration):
577    '''Represents an enum.
578
579    @type _values: dict of str => int
580    @ivar _values: holds the values for this enum.
581    '''
582   
583    def __init__(self, name, namespace):
584        Declaration.__init__(self, name, namespace)
585        self.values = {} # dict of str => int
586
587
588    def ValueFullName(self, name):
589        '''Returns the full name for a value in the enum.
590        '''
591        assert name in self.values
592        namespace = self.namespace
593        if namespace:
594            namespace += '::'
595        return namespace + name
596
597
598#==============================================================================
599# ClassEnumeration
600#==============================================================================
601class ClassEnumeration(Enumeration):
602    '''Represents an enum inside a class.
603
604    @ivar _class: The full name of the class where this enum belongs.
605    @ivar _visibility: The visibility of this enum inside his class.
606    '''
607
608    def __init__(self, name, class_, visib):
609        Enumeration.__init__(self, name, None)
610        self.class_ = class_
611        self.visibility = visib
612
613
614    def FullName(self):
615        return '%s::%s' % (self.class_, self.name)
616
617
618    def ValueFullName(self, name):
619        assert name in self.values
620        return '%s::%s' % (self.class_, name)
621
622   
623#==============================================================================
624# Typedef
625#==============================================================================
626class Typedef(Declaration):
627    '''A Typedef declaration.
628
629    @type _type: L{Type}
630    @ivar _type: The type of the typedef.
631
632    @type _visibility: L{Scope}
633    @ivar _visibility: The visibility of this typedef.
634    '''
635
636    def __init__(self, type, name, namespace):
637        Declaration.__init__(self, name, namespace)
638        self.type = type
639        self.visibility = Scope.public
640
641
642
643
644                         
645#==============================================================================
646# Unknown       
647#==============================================================================
648class Unknown(Declaration):
649    '''A declaration that Pyste does not know how to handle.
650    '''
651
652    def __init__(self, name):
653        Declaration.__init__(self, name, None)
Note: See TracBrowser for help on using the repository browser.