OSDN Git Service

2009-07-16 Phil Muldoon <pmuldoon@redhat.com>
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / python / libstdcxx / v6 / printers.py
1 # Pretty-printers for libstc++.
2
3 # Copyright (C) 2008, 2009 Free Software Foundation, Inc.
4
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 import gdb
19 import itertools
20 import re
21
22 class StdPointerPrinter:
23     "Print a smart pointer of some kind"
24
25     def __init__ (self, typename, val):
26         self.typename = typename
27         self.val = val
28
29     def to_string (self):
30         if self.val['_M_refcount']['_M_pi'] == 0:
31             return '%s (empty) %s' % (self.typename, self.val['_M_ptr'])
32         return '%s (count %d) %s' % (self.typename,
33                                      self.val['_M_refcount']['_M_pi']['_M_use_count'],
34                                      self.val['_M_ptr'])
35
36 class UniquePointerPrinter:
37     "Print a unique_ptr"
38
39     def __init__ (self, val):
40         self.val = val
41
42     def to_string (self):
43         return self.val['_M_t']
44
45 class StdListPrinter:
46     "Print a std::list"
47
48     class _iterator:
49         def __init__(self, nodetype, head):
50             self.nodetype = nodetype
51             self.base = head['_M_next']
52             self.head = head.address
53             self.count = 0
54
55         def __iter__(self):
56             return self
57
58         def next(self):
59             if self.base == self.head:
60                 raise StopIteration
61             elt = self.base.cast(self.nodetype).dereference()
62             self.base = elt['_M_next']
63             count = self.count
64             self.count = self.count + 1
65             return ('[%d]' % count, elt['_M_data'])
66
67     def __init__(self, val):
68         self.val = val
69
70     def children(self):
71         itype = self.val.type.template_argument(0)
72         nodetype = gdb.lookup_type('std::_List_node<%s>' % itype).pointer()
73         return self._iterator(nodetype, self.val['_M_impl']['_M_node'])
74
75     def to_string(self):
76         if self.val['_M_impl']['_M_node'].address == self.val['_M_impl']['_M_node']['_M_next']:
77             return 'empty std::list'
78         return 'std::list'
79
80 class StdListIteratorPrinter:
81     "Print std::list::iterator"
82
83     def __init__(self, val):
84         self.val = val
85
86     def to_string(self):
87         itype = self.val.type.template_argument(0)
88         nodetype = gdb.lookup_type('std::_List_node<%s>' % itype).pointer()
89         return self.val['_M_node'].cast(nodetype).dereference()['_M_data']
90
91 class StdSlistPrinter:
92     "Print a __gnu_cxx::slist"
93
94     class _iterator:
95         def __init__(self, nodetype, head):
96             self.nodetype = nodetype
97             self.base = head['_M_head']['_M_next']
98             self.count = 0
99
100         def __iter__(self):
101             return self
102
103         def next(self):
104             if self.base == 0:
105                 raise StopIteration
106             elt = self.base.cast(self.nodetype).dereference()
107             self.base = elt['_M_next']
108             count = self.count
109             self.count = self.count + 1
110             return ('[%d]' % count, elt['_M_data'])
111
112     def __init__(self, val):
113         self.val = val
114
115     def children(self):
116         itype = self.val.type.template_argument(0)
117         nodetype = gdb.lookup_type('__gnu_cxx::_Slist_node<%s>' % itype).pointer()
118         return self._iterator(nodetype, self.val)
119
120     def to_string(self):
121         if self.val['_M_head']['_M_next'] == 0:
122             return 'empty __gnu_cxx::slist'
123         return '__gnu_cxx::slist'
124
125 class StdSlistIteratorPrinter:
126     "Print __gnu_cxx::slist::iterator"
127
128     def __init__(self, val):
129         self.val = val
130
131     def to_string(self):
132         itype = self.val.type.template_argument(0)
133         nodetype = gdb.lookup_type('__gnu_cxx::_Slist_node<%s>' % itype).pointer()
134         return self.val['_M_node'].cast(nodetype).dereference()['_M_data']
135
136 class StdVectorPrinter:
137     "Print a std::vector"
138
139     class _iterator:
140         def __init__ (self, start, finish):
141             self.item = start
142             self.finish = finish
143             self.count = 0
144
145         def __iter__(self):
146             return self
147
148         def next(self):
149             if self.item == self.finish:
150                 raise StopIteration
151             count = self.count
152             self.count = self.count + 1
153             elt = self.item.dereference()
154             self.item = self.item + 1
155             return ('[%d]' % count, elt)
156
157     def __init__(self, val):
158         self.val = val
159
160     def children(self):
161         return self._iterator(self.val['_M_impl']['_M_start'],
162                               self.val['_M_impl']['_M_finish'])
163
164     def to_string(self):
165         start = self.val['_M_impl']['_M_start']
166         finish = self.val['_M_impl']['_M_finish']
167         end = self.val['_M_impl']['_M_end_of_storage']
168         return ('std::vector of length %d, capacity %d'
169                 % (int (finish - start), int (end - start)))
170
171     def display_hint(self):
172         return 'array'
173
174 class StdVectorIteratorPrinter:
175     "Print std::vector::iterator"
176
177     def __init__(self, val):
178         self.val = val
179
180     def to_string(self):
181         return self.val['_M_current'].dereference()
182
183 class StdStackOrQueuePrinter:
184     "Print a std::stack or std::queue"
185
186     def __init__ (self, typename, val):
187         self.typename = typename
188         self.visualizer = gdb.default_visualizer(val['c'])
189
190     def children (self):
191         return self.visualizer.children()
192
193     def to_string (self):
194         return '%s wrapping: %s' % (self.typename,
195                                     self.visualizer.to_string())
196
197     def display_hint (self):
198         if hasattr (self.visualizer, 'display_hint'):
199             return self.visualizer.display_hint ()
200         return None
201
202 class RbtreeIterator:
203     def __init__(self, rbtree):
204         self.size = rbtree['_M_t']['_M_impl']['_M_node_count']
205         self.node = rbtree['_M_t']['_M_impl']['_M_header']['_M_left']
206         self.count = 0
207
208     def __iter__(self):
209         return self
210
211     def __len__(self):
212         return int (self.size)
213
214     def next(self):
215         if self.count == self.size:
216             raise StopIteration
217         result = self.node
218         self.count = self.count + 1
219         if self.count < self.size:
220             # Compute the next node.
221             node = self.node
222             if node.dereference()['_M_right']:
223                 node = node.dereference()['_M_right']
224                 while node.dereference()['_M_left']:
225                     node = node.dereference()['_M_left']
226             else:
227                 parent = node.dereference()['_M_parent']
228                 while node == parent.dereference()['_M_right']:
229                     node = parent
230                     parent = parent.dereference()['_M_parent']
231                 if node.dereference()['_M_right'] != parent:
232                     node = parent
233             self.node = node
234         return result
235
236 # This is a pretty printer for std::_Rb_tree_iterator (which is
237 # std::map::iterator), and has nothing to do with the RbtreeIterator
238 # class above.
239 class StdRbtreeIteratorPrinter:
240     "Print std::map::iterator"
241
242     def __init__ (self, val):
243         self.val = val
244
245     def to_string (self):
246         valuetype = self.val.type.template_argument(0)
247         nodetype = gdb.lookup_type('std::_Rb_tree_node < %s >' % valuetype)
248         nodetype = nodetype.pointer()
249         return self.val.cast(nodetype).dereference()['_M_value_field']
250
251
252 class StdMapPrinter:
253     "Print a std::map or std::multimap"
254
255     # Turn an RbtreeIterator into a pretty-print iterator.
256     class _iter:
257         def __init__(self, rbiter, type):
258             self.rbiter = rbiter
259             self.count = 0
260             self.type = type
261
262         def __iter__(self):
263             return self
264
265         def next(self):
266             if self.count % 2 == 0:
267                 n = self.rbiter.next()
268                 n = n.cast(self.type).dereference()['_M_value_field']
269                 self.pair = n
270                 item = n['first']
271             else:
272                 item = self.pair['second']
273             result = ('[%d]' % self.count, item)
274             self.count = self.count + 1
275             return result
276
277     def __init__ (self, typename, val):
278         self.typename = typename
279         self.val = val
280
281     def to_string (self):
282         return '%s with %d elements' % (self.typename,
283                                         len (RbtreeIterator (self.val)))
284
285     def children (self):
286         keytype = self.val.type.template_argument(0).const()
287         valuetype = self.val.type.template_argument(1)
288         nodetype = gdb.lookup_type('std::_Rb_tree_node< std::pair< %s, %s > >' % (keytype, valuetype))
289         nodetype = nodetype.pointer()
290         return self._iter (RbtreeIterator (self.val), nodetype)
291
292     def display_hint (self):
293         return 'map'
294
295 class StdSetPrinter:
296     "Print a std::set or std::multiset"
297
298     # Turn an RbtreeIterator into a pretty-print iterator.
299     class _iter:
300         def __init__(self, rbiter, type):
301             self.rbiter = rbiter
302             self.count = 0
303             self.type = type
304
305         def __iter__(self):
306             return self
307
308         def next(self):
309             item = self.rbiter.next()
310             item = item.cast(self.type).dereference()['_M_value_field']
311             # FIXME: this is weird ... what to do?
312             # Maybe a 'set' display hint?
313             result = ('[%d]' % self.count, item)
314             self.count = self.count + 1
315             return result
316
317     def __init__ (self, typename, val):
318         self.typename = typename
319         self.val = val
320
321     def to_string (self):
322         return '%s with %d elements' % (self.typename,
323                                         len (RbtreeIterator (self.val)))
324
325     def children (self):
326         keytype = self.val.type.template_argument(0)
327         nodetype = gdb.lookup_type('std::_Rb_tree_node< %s >' % keytype).pointer()
328         return self._iter (RbtreeIterator (self.val), nodetype)
329
330 class StdBitsetPrinter:
331     "Print a std::bitset"
332
333     def __init__(self, val):
334         self.val = val
335
336     def to_string (self):
337         # If template_argument handled values, we could print the
338         # size.  Or we could use a regexp on the type.
339         return 'std::bitset'
340
341     def children (self):
342         words = self.val['_M_w']
343         wtype = words.type
344
345         # The _M_w member can be either an unsigned long, or an
346         # array.  This depends on the template specialization used.
347         # If it is a single long, convert to a single element list.
348         if wtype.code == gdb.TYPE_CODE_ARRAY:
349             tsize = wtype.target ().sizeof
350         else:
351             words = [words]
352             tsize = wtype.sizeof 
353
354         nwords = wtype.sizeof / tsize
355         result = []
356         byte = 0
357         while byte < nwords:
358             w = words[byte]
359             bit = 0
360             while w != 0:
361                 if (w & 1) != 0:
362                     # Another spot where we could use 'set'?
363                     result.append(('[%d]' % (byte * tsize * 8 + bit), 1))
364                 bit = bit + 1
365                 w = w >> 1
366             byte = byte + 1
367         return result
368
369 class StdDequePrinter:
370     "Print a std::deque"
371
372     class _iter:
373         def __init__(self, node, start, end, last, buffer_size):
374             self.node = node
375             self.p = start
376             self.end = end
377             self.last = last
378             self.buffer_size = buffer_size
379             self.count = 0
380
381         def __iter__(self):
382             return self
383
384         def next(self):
385             if self.p == self.last:
386                 raise StopIteration
387
388             result = ('[%d]' % self.count, self.p.dereference())
389             self.count = self.count + 1
390
391             # Advance the 'cur' pointer.
392             self.p = self.p + 1
393             if self.p == self.end:
394                 # If we got to the end of this bucket, move to the
395                 # next bucket.
396                 self.node = self.node + 1
397                 self.p = self.node[0]
398                 self.end = self.p + self.buffer_size
399
400             return result
401
402     def __init__(self, val):
403         self.val = val
404         self.elttype = val.type.template_argument(0)
405         size = self.elttype.sizeof
406         if size < 512:
407             self.buffer_size = int (512 / size)
408         else:
409             self.buffer_size = 1
410
411     def to_string(self):
412         start = self.val['_M_impl']['_M_start']
413         end = self.val['_M_impl']['_M_finish']
414
415         delta_n = end['_M_node'] - start['_M_node'] - 1
416         delta_s = start['_M_last'] - start['_M_cur']
417         delta_e = end['_M_cur'] - end['_M_first']
418
419         size = self.buffer_size * delta_n + delta_s + delta_e
420
421         return 'std::deque with %d elements' % long (size)
422
423     def children(self):
424         start = self.val['_M_impl']['_M_start']
425         end = self.val['_M_impl']['_M_finish']
426         return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
427                           end['_M_cur'], self.buffer_size)
428
429     def display_hint (self):
430         return 'array'
431
432 class StdDequeIteratorPrinter:
433     "Print std::deque::iterator"
434
435     def __init__(self, val):
436         self.val = val
437
438     def to_string(self):
439         return self.val['_M_cur'].dereference()
440
441 class StdStringPrinter:
442     "Print a std::basic_string of some kind"
443
444     def __init__(self, encoding, val):
445         self.encoding = encoding
446         self.val = val
447
448     def to_string(self):
449         # Look up the target encoding as late as possible.
450         encoding = self.encoding
451         if encoding == 0:
452             encoding = gdb.parameter('target-charset')
453         elif encoding == 1:
454             encoding = gdb.parameter('target-wide-charset')
455
456         # Make sure &string works, too.
457         type = self.val.type
458         if type.code == gdb.TYPE_CODE_REF:
459             type = type.target ()
460
461         # Calculate the length of the string so that to_string returns
462         # the string according to length, not according to first null
463         # encountered.
464         ptr = self.val ['_M_dataplus']['_M_p']
465         realtype = type.unqualified ().strip_typedefs ()
466         reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
467         header = ptr.cast(reptype) - 1
468         len = header.dereference ()['_M_length']
469         return self.val['_M_dataplus']['_M_p'].string (encoding, length = len)
470
471     def display_hint (self):
472         return 'string'
473
474 class Tr1HashtableIterator:
475     def __init__ (self, hash):
476         self.count = 0
477         self.n_buckets = hash['_M_element_count']
478         if self.n_buckets == 0:
479             self.node = False
480         else:
481             self.bucket = hash['_M_buckets']
482             self.node = self.bucket[0]
483             self.update ()
484
485     def __iter__ (self):
486         return self
487
488     def update (self):
489         # If we advanced off the end of the chain, move to the next
490         # bucket.
491         while self.node == 0:
492             self.bucket = self.bucket + 1
493             self.node = self.bucket[0]
494
495        # If we advanced off the end of the bucket array, then
496        # we're done.
497         if self.count == self.n_buckets:
498             self.node = False
499         else:
500             self.count = self.count + 1
501
502     def next (self):
503         if not self.node:
504             raise StopIteration
505         result = self.node.dereference()['_M_v']
506         self.node = self.node.dereference()['_M_next']
507         self.update ()
508         return result
509
510 class Tr1UnorderedSetPrinter:
511     "Print a tr1::unordered_set"
512
513     def __init__ (self, typename, val):
514         self.typename = typename
515         self.val = val
516
517     def to_string (self):
518         return '%s with %d elements' % (self.typename, self.val['_M_element_count'])
519
520     @staticmethod
521     def format_count (i):
522         return '[%d]' % i
523
524     def children (self):
525         counter = itertools.imap (self.format_count, itertools.count())
526         return itertools.izip (counter, Tr1HashtableIterator (self.val))
527
528 class Tr1UnorderedMapPrinter:
529     "Print a tr1::unordered_map"
530
531     def __init__ (self, typename, val):
532         self.typename = typename
533         self.val = val
534
535     def to_string (self):
536         return '%s with %d elements' % (self.typename, self.val['_M_element_count'])
537
538     @staticmethod
539     def flatten (list):
540         for elt in list:
541             for i in elt:
542                 yield i
543
544     @staticmethod
545     def format_one (elt):
546         return (elt['first'], elt['second'])
547
548     @staticmethod
549     def format_count (i):
550         return '[%d]' % i
551
552     def children (self):
553         counter = itertools.imap (self.format_count, itertools.count())
554         # Map over the hash table and flatten the result.
555         data = self.flatten (itertools.imap (self.format_one, Tr1HashtableIterator (self.val)))
556         # Zip the two iterators together.
557         return itertools.izip (counter, data)
558
559     def display_hint (self):
560         return 'map'
561
562 def register_libstdcxx_printers (obj):
563     "Register libstdc++ pretty-printers with objfile Obj."
564
565     if obj == None:
566         obj = gdb
567
568     obj.pretty_printers.append (lookup_function)
569
570 def lookup_function (val):
571     "Look-up and return a pretty-printer that can print val."
572
573     # Get the type.
574     type = val.type
575
576     # If it points to a reference, get the reference.
577     if type.code == gdb.TYPE_CODE_REF:
578         type = type.target ()
579
580     # Get the unqualified type, stripped of typedefs.
581     type = type.unqualified ().strip_typedefs ()
582
583     # Get the type name.    
584     typename = type.tag
585     if typename == None:
586         return None
587
588     # Iterate over local dictionary of types to determine
589     # if a printer is registered for that type.  Return an
590     # instantiation of the printer if found.
591     for function in pretty_printers_dict:
592         if function.search (typename):
593             return pretty_printers_dict[function] (val)
594         
595     # Cannot find a pretty printer.  Return None.
596     return None
597
598 def build_libstdcxx_dictionary ():
599     # libstdc++ objects requiring pretty-printing.
600     # In order from:
601     # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
602     pretty_printers_dict[re.compile('^std::basic_string<char(,.*)?>$')] = lambda val: StdStringPrinter(0, val)
603     pretty_printers_dict[re.compile('^std::basic_string<wchar_t(,.*)?>$')] = lambda val: StdStringPrinter(1, val)
604     pretty_printers_dict[re.compile('^std::basic_string<char16_t(,.*)?>$')] = lambda val: StdStringPrinter('UTF-16', val)
605     pretty_printers_dict[re.compile('^std::basic_string<char32_t(,.*)?>$')] = lambda val: StdStringPrinter('UTF-32', val)
606     pretty_printers_dict[re.compile('^std::bitset<.*>$')] = StdBitsetPrinter
607     pretty_printers_dict[re.compile('^std::deque<.*>$')] = StdDequePrinter
608     pretty_printers_dict[re.compile('^std::list<.*>$')] = StdListPrinter
609     pretty_printers_dict[re.compile('^std::map<.*>$')] = lambda val: StdMapPrinter("std::map", val)
610     pretty_printers_dict[re.compile('^std::multimap<.*>$')] = lambda val: StdMapPrinter("std::multimap", val)
611     pretty_printers_dict[re.compile('^std::multiset<.*>$')] = lambda val: StdSetPrinter("std::multiset", val)
612     pretty_printers_dict[re.compile('^std::priority_queue<.*>$')] = lambda val: StdStackOrQueuePrinter("std::priority_queue", val)
613     pretty_printers_dict[re.compile('^std::queue<.*>$')] = lambda val: StdStackOrQueuePrinter("std::queue", val)
614     pretty_printers_dict[re.compile('^std::set<.*>$')] = lambda val: StdSetPrinter("std::set", val)
615     pretty_printers_dict[re.compile('^std::stack<.*>$')] = lambda val: StdStackOrQueuePrinter("std::stack", val)
616     pretty_printers_dict[re.compile('^std::unique_ptr<.*>$')] = UniquePointerPrinter
617     pretty_printers_dict[re.compile('^std::vector<.*>$')] = StdVectorPrinter
618     # vector<bool>
619
620     # These are the TR1 and C++0x printers.
621     # For array - the default GDB pretty-printer seems reasonable.
622     pretty_printers_dict[re.compile('^std::shared_ptr<.*>$')] = lambda val: StdPointerPrinter ('std::shared_ptr', val)
623     pretty_printers_dict[re.compile('^std::weak_ptr<.*>$')] = lambda val: StdPointerPrinter ('std::weak_ptr', val)
624     pretty_printers_dict[re.compile('^std::unordered_map<.*>$')] = lambda val: Tr1UnorderedMapPrinter ('std::unordered_map', val)
625     pretty_printers_dict[re.compile('^std::unordered_set<.*>$')] = lambda val: Tr1UnorderedSetPrinter ('std::unordered_set', val)
626     pretty_printers_dict[re.compile('^std::unordered_multimap<.*>$')] = lambda val: Tr1UnorderedMapPrinter ('std::unordered_multimap', val)
627     pretty_printers_dict[re.compile('^std::unordered_multiset<.*>$')] = lambda val: Tr1UnorderedSetPrinter ('std::unordered_multiset', val)
628
629     pretty_printers_dict[re.compile('^std::tr1::shared_ptr<.*>$')] = lambda val: StdPointerPrinter ('std::tr1::shared_ptr', val)
630     pretty_printers_dict[re.compile('^std::tr1::weak_ptr<.*>$')] = lambda val: StdPointerPrinter ('std::tr1::weak_ptr', val)
631     pretty_printers_dict[re.compile('^std::tr1::unordered_map<.*>$')] = lambda val: Tr1UnorderedMapPrinter ('std::tr1::unordered_map', val)
632     pretty_printers_dict[re.compile('^std::tr1::unordered_set<.*>$')] = lambda val: Tr1UnorderedSetPrinter ('std::tr1::unordered_set', val)
633     pretty_printers_dict[re.compile('^std::tr1::unordered_multimap<.*>$')] = lambda val: Tr1UnorderedMapPrinter ('std::tr1::unordered_multimap', val)
634     pretty_printers_dict[re.compile('^std::tr1::unordered_multiset<.*>$')] = lambda val: Tr1UnorderedSetPrinter ('std::tr1::unordered_multiset', val)
635
636
637     # Extensions.
638     pretty_printers_dict[re.compile('^__gnu_cxx::slist<.*>$')] = StdSlistPrinter
639
640     if True:
641         # These shouldn't be necessary, if GDB "print *i" worked.
642         # But it often doesn't, so here they are.
643         pretty_printers_dict[re.compile('^std::_List_iterator<.*>$')] = lambda val: StdListIteratorPrinter(val)
644         pretty_printers_dict[re.compile('^std::_List_const_iterator<.*>$')] = lambda val: StdListIteratorPrinter(val)
645         pretty_printers_dict[re.compile('^std::_Rb_tree_iterator<.*>$')] = lambda val: StdRbtreeIteratorPrinter(val)
646         pretty_printers_dict[re.compile('^std::_Rb_tree_const_iterator<.*>$')] = lambda val: StdRbtreeIteratorPrinter(val)
647         pretty_printers_dict[re.compile('^std::_Deque_iterator<.*>$')] = lambda val: StdDequeIteratorPrinter(val)
648         pretty_printers_dict[re.compile('^std::_Deque_const_iterator<.*>$')] = lambda val: StdDequeIteratorPrinter(val)
649         pretty_printers_dict[re.compile('^__gnu_cxx::__normal_iterator<.*>$')] = lambda val: StdVectorIteratorPrinter(val)
650         pretty_printers_dict[re.compile('^__gnu_cxx::_Slist_iterator<.*>$')] = lambda val: StdSlistIteratorPrinter(val)
651
652 pretty_printers_dict = {}
653
654 build_libstdcxx_dictionary ()