OSDN Git Service

* python/libstdcxx/v6/printers.py (lookup_function): Remove extra
[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         self.iter = RbtreeIterator (val)
281
282     def to_string (self):
283         return '%s with %d elements' % (self.typename, len (self.iter))
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 (self.iter, 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         self.iter = RbtreeIterator (val)
321
322     def to_string (self):
323         return '%s with %d elements' % (self.typename, len (self.iter))
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 (self.iter, 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         return self.val['_M_dataplus']['_M_p'].string(encoding)
456
457     def display_hint (self):
458         return 'string'
459
460 class Tr1HashtableIterator:
461     def __init__ (self, hash):
462         self.count = 0
463         self.n_buckets = hash['_M_element_count']
464         if self.n_buckets == 0:
465             self.node = False
466         else:
467             self.bucket = hash['_M_buckets']
468             self.node = self.bucket[0]
469             self.update ()
470
471     def __iter__ (self):
472         return self
473
474     def update (self):
475         # If we advanced off the end of the chain, move to the next
476         # bucket.
477         while self.node == 0:
478             self.bucket = self.bucket + 1
479             self.node = self.bucket[0]
480
481        # If we advanced off the end of the bucket array, then
482        # we're done.
483         if self.count == self.n_buckets:
484             self.node = False
485         else:
486             self.count = self.count + 1
487
488     def next (self):
489         if not self.node:
490             raise StopIteration
491         result = self.node.dereference()['_M_v']
492         self.node = self.node.dereference()['_M_next']
493         self.update ()
494         return result
495
496 class Tr1UnorderedSetPrinter:
497     "Print a tr1::unordered_set"
498
499     def __init__ (self, typename, val):
500         self.typename = typename
501         self.val = val
502
503     def to_string (self):
504         return '%s with %d elements' % (self.typename, self.val['_M_element_count'])
505
506     @staticmethod
507     def format_count (i):
508         return '[%d]' % i
509
510     def children (self):
511         counter = itertools.imap (self.format_count, itertools.count())
512         return itertools.izip (counter, Tr1HashtableIterator (self.val))
513
514 class Tr1UnorderedMapPrinter:
515     "Print a tr1::unordered_map"
516
517     def __init__ (self, typename, val):
518         self.typename = typename
519         self.val = val
520
521     def to_string (self):
522         return '%s with %d elements' % (self.typename, self.val['_M_element_count'])
523
524     @staticmethod
525     def flatten (list):
526         for elt in list:
527             for i in elt:
528                 yield i
529
530     @staticmethod
531     def format_one (elt):
532         return (elt['first'], elt['second'])
533
534     @staticmethod
535     def format_count (i):
536         return '[%d]' % i
537
538     def children (self):
539         counter = itertools.imap (self.format_count, itertools.count())
540         # Map over the hash table and flatten the result.
541         data = self.flatten (itertools.imap (self.format_one, Tr1HashtableIterator (self.val)))
542         # Zip the two iterators together.
543         return itertools.izip (counter, data)
544
545     def display_hint (self):
546         return 'map'
547
548 def register_libstdcxx_printers (obj):
549     "Register libstdc++ pretty-printers with objfile Obj."
550
551     if obj == None:
552         obj = gdb
553
554     obj.pretty_printers.append (lookup_function)
555
556 def lookup_function (val):
557     "Look-up and return a pretty-printer that can print val."
558
559     # Get the type.
560     type = val.type
561
562     # If it points to a reference, get the reference.
563     if type.code == gdb.TYPE_CODE_REF:
564         type = type.target ()
565
566     # Get the unqualified type, stripped of typedefs.
567     type = type.unqualified ().strip_typedefs ()
568
569     # Get the type name.    
570     typename = type.tag
571     if typename == None:
572         return None
573
574     # Iterate over local dictionary of types to determine
575     # if a printer is registered for that type.  Return an
576     # instantiation of the printer if found.
577     for function in pretty_printers_dict:
578         if function.search (typename):
579             return pretty_printers_dict[function] (val)
580         
581     # Cannot find a pretty printer.  Return None.
582     return None
583
584 def build_libstdcxx_dictionary ():
585     # libstdc++ objects requiring pretty-printing.
586     # In order from:
587     # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
588     pretty_printers_dict[re.compile('^std::basic_string<char(,.*)?>$')] = lambda val: StdStringPrinter(0, val)
589     pretty_printers_dict[re.compile('^std::basic_string<wchar_t(,.*)?>$')] = lambda val: StdStringPrinter(1, val)
590     pretty_printers_dict[re.compile('^std::basic_string<char16_t(,.*)?>$')] = lambda val: StdStringPrinter('UTF-16', val)
591     pretty_printers_dict[re.compile('^std::basic_string<char32_t(,.*)?>$')] = lambda val: StdStringPrinter('UTF-32', val)
592     pretty_printers_dict[re.compile('^std::bitset<.*>$')] = StdBitsetPrinter
593     pretty_printers_dict[re.compile('^std::deque<.*>$')] = StdDequePrinter
594     pretty_printers_dict[re.compile('^std::list<.*>$')] = StdListPrinter
595     pretty_printers_dict[re.compile('^std::map<.*>$')] = lambda val: StdMapPrinter("std::map", val)
596     pretty_printers_dict[re.compile('^std::multimap<.*>$')] = lambda val: StdMapPrinter("std::multimap", val)
597     pretty_printers_dict[re.compile('^std::multiset<.*>$')] = lambda val: StdSetPrinter("std::multiset", val)
598     pretty_printers_dict[re.compile('^std::priority_queue<.*>$')] = lambda val: StdStackOrQueuePrinter("std::priority_queue", val)
599     pretty_printers_dict[re.compile('^std::queue<.*>$')] = lambda val: StdStackOrQueuePrinter("std::queue", val)
600     pretty_printers_dict[re.compile('^std::set<.*>$')] = lambda val: StdSetPrinter("std::set", val)
601     pretty_printers_dict[re.compile('^std::stack<.*>$')] = lambda val: StdStackOrQueuePrinter("std::stack", val)
602     pretty_printers_dict[re.compile('^std::unique_ptr<.*>$')] = UniquePointerPrinter
603     pretty_printers_dict[re.compile('^std::vector<.*>$')] = StdVectorPrinter
604     # vector<bool>
605
606     # These are the TR1 and C++0x printers.
607     # For array - the default GDB pretty-printer seems reasonable.
608     pretty_printers_dict[re.compile('^std::shared_ptr<.*>$')] = lambda val: StdPointerPrinter ('std::shared_ptr', val)
609     pretty_printers_dict[re.compile('^std::weak_ptr<.*>$')] = lambda val: StdPointerPrinter ('std::weak_ptr', val)
610     pretty_printers_dict[re.compile('^std::unordered_map<.*>$')] = lambda val: Tr1UnorderedMapPrinter ('std::unordered_map', val)
611     pretty_printers_dict[re.compile('^std::unordered_set<.*>$')] = lambda val: Tr1UnorderedSetPrinter ('std::unordered_set', val)
612     pretty_printers_dict[re.compile('^std::unordered_multimap<.*>$')] = lambda val: Tr1UnorderedMapPrinter ('std::unordered_multimap', val)
613     pretty_printers_dict[re.compile('^std::unordered_multiset<.*>$')] = lambda val: Tr1UnorderedSetPrinter ('std::unordered_multiset', val)
614
615     pretty_printers_dict[re.compile('^std::tr1::shared_ptr<.*>$')] = lambda val: StdPointerPrinter ('std::tr1::shared_ptr', val)
616     pretty_printers_dict[re.compile('^std::tr1::weak_ptr<.*>$')] = lambda val: StdPointerPrinter ('std::tr1::weak_ptr', val)
617     pretty_printers_dict[re.compile('^std::tr1::unordered_map<.*>$')] = lambda val: Tr1UnorderedMapPrinter ('std::tr1::unordered_map', val)
618     pretty_printers_dict[re.compile('^std::tr1::unordered_set<.*>$')] = lambda val: Tr1UnorderedSetPrinter ('std::tr1::unordered_set', val)
619     pretty_printers_dict[re.compile('^std::tr1::unordered_multimap<.*>$')] = lambda val: Tr1UnorderedMapPrinter ('std::tr1::unordered_multimap', val)
620     pretty_printers_dict[re.compile('^std::tr1::unordered_multiset<.*>$')] = lambda val: Tr1UnorderedSetPrinter ('std::tr1::unordered_multiset', val)
621
622
623     # Extensions.
624     pretty_printers_dict[re.compile('^__gnu_cxx::slist<.*>$')] = StdSlistPrinter
625
626     if True:
627         # These shouldn't be necessary, if GDB "print *i" worked.
628         # But it often doesn't, so here they are.
629         pretty_printers_dict[re.compile('^std::_List_iterator<.*>$')] = lambda val: StdListIteratorPrinter(val)
630         pretty_printers_dict[re.compile('^std::_List_const_iterator<.*>$')] = lambda val: StdListIteratorPrinter(val)
631         pretty_printers_dict[re.compile('^std::_Rb_tree_iterator<.*>$')] = lambda val: StdRbtreeIteratorPrinter(val)
632         pretty_printers_dict[re.compile('^std::_Rb_tree_const_iterator<.*>$')] = lambda val: StdRbtreeIteratorPrinter(val)
633         pretty_printers_dict[re.compile('^std::_Deque_iterator<.*>$')] = lambda val: StdDequeIteratorPrinter(val)
634         pretty_printers_dict[re.compile('^std::_Deque_const_iterator<.*>$')] = lambda val: StdDequeIteratorPrinter(val)
635         pretty_printers_dict[re.compile('^__gnu_cxx::__normal_iterator<.*>$')] = lambda val: StdVectorIteratorPrinter(val)
636         pretty_printers_dict[re.compile('^__gnu_cxx::_Slist_iterator<.*>$')] = lambda val: StdSlistIteratorPrinter(val)
637
638 pretty_printers_dict = {}
639
640 build_libstdcxx_dictionary ()