]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/libstdc++-v3/contrib/libstdc++-v3-4.8/python/libstdcxx/v6/printers.py
update
[l4.git] / l4 / pkg / libstdc++-v3 / contrib / libstdc++-v3-4.8 / python / libstdcxx / v6 / printers.py
1 # Pretty-printers for libstc++.
2
3 # Copyright (C) 2008-2013 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 # Try to use the new-style pretty-printing if available.
23 _use_gdb_pp = True
24 try:
25     import gdb.printing
26 except ImportError:
27     _use_gdb_pp = False
28
29 # Try to install type-printers.
30 _use_type_printing = False
31 try:
32     import gdb.types
33     if hasattr(gdb.types, 'TypePrinter'):
34         _use_type_printing = True
35 except ImportError:
36     pass
37
38 # Starting with the type ORIG, search for the member type NAME.  This
39 # handles searching upward through superclasses.  This is needed to
40 # work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
41 def find_type(orig, name):
42     typ = orig.strip_typedefs()
43     while True:
44         search = str(typ) + '::' + name
45         try:
46             return gdb.lookup_type(search)
47         except RuntimeError:
48             pass
49         # The type was not found, so try the superclass.  We only need
50         # to check the first superclass, so we don't bother with
51         # anything fancier here.
52         field = typ.fields()[0]
53         if not field.is_base_class:
54             raise ValueError, "Cannot find type %s::%s" % (str(orig), name)
55         typ = field.type
56
57 class SharedPointerPrinter:
58     "Print a shared_ptr or weak_ptr"
59
60     def __init__ (self, typename, val):
61         self.typename = typename
62         self.val = val
63
64     def to_string (self):
65         state = 'empty'
66         refcounts = self.val['_M_refcount']['_M_pi']
67         if refcounts != 0:
68             usecount = refcounts['_M_use_count']
69             weakcount = refcounts['_M_weak_count']
70             if usecount == 0:
71                 state = 'expired, weak %d' % weakcount
72             else:
73                 state = 'count %d, weak %d' % (usecount, weakcount - 1)
74         return '%s (%s) %s' % (self.typename, state, self.val['_M_ptr'])
75
76 class UniquePointerPrinter:
77     "Print a unique_ptr"
78
79     def __init__ (self, typename, val):
80         self.val = val
81
82     def to_string (self):
83         v = self.val['_M_t']['_M_head_impl']
84         return ('std::unique_ptr<%s> containing %s' % (str(v.type.target()),
85                                                        str(v)))
86
87 class StdListPrinter:
88     "Print a std::list"
89
90     class _iterator:
91         def __init__(self, nodetype, head):
92             self.nodetype = nodetype
93             self.base = head['_M_next']
94             self.head = head.address
95             self.count = 0
96
97         def __iter__(self):
98             return self
99
100         def next(self):
101             if self.base == self.head:
102                 raise StopIteration
103             elt = self.base.cast(self.nodetype).dereference()
104             self.base = elt['_M_next']
105             count = self.count
106             self.count = self.count + 1
107             return ('[%d]' % count, elt['_M_data'])
108
109     def __init__(self, typename, val):
110         self.typename = typename
111         self.val = val
112
113     def children(self):
114         nodetype = find_type(self.val.type, '_Node')
115         nodetype = nodetype.strip_typedefs().pointer()
116         return self._iterator(nodetype, self.val['_M_impl']['_M_node'])
117
118     def to_string(self):
119         if self.val['_M_impl']['_M_node'].address == self.val['_M_impl']['_M_node']['_M_next']:
120             return 'empty %s' % (self.typename)
121         return '%s' % (self.typename)
122
123 class StdListIteratorPrinter:
124     "Print std::list::iterator"
125
126     def __init__(self, typename, val):
127         self.val = val
128         self.typename = typename
129
130     def to_string(self):
131         nodetype = find_type(self.val.type, '_Node')
132         nodetype = nodetype.strip_typedefs().pointer()
133         return self.val['_M_node'].cast(nodetype).dereference()['_M_data']
134
135 class StdSlistPrinter:
136     "Print a __gnu_cxx::slist"
137
138     class _iterator:
139         def __init__(self, nodetype, head):
140             self.nodetype = nodetype
141             self.base = head['_M_head']['_M_next']
142             self.count = 0
143
144         def __iter__(self):
145             return self
146
147         def next(self):
148             if self.base == 0:
149                 raise StopIteration
150             elt = self.base.cast(self.nodetype).dereference()
151             self.base = elt['_M_next']
152             count = self.count
153             self.count = self.count + 1
154             return ('[%d]' % count, elt['_M_data'])
155
156     def __init__(self, typename, val):
157         self.val = val
158
159     def children(self):
160         nodetype = find_type(self.val.type, '_Node')
161         nodetype = nodetype.strip_typedefs().pointer()
162         return self._iterator(nodetype, self.val)
163
164     def to_string(self):
165         if self.val['_M_head']['_M_next'] == 0:
166             return 'empty __gnu_cxx::slist'
167         return '__gnu_cxx::slist'
168
169 class StdSlistIteratorPrinter:
170     "Print __gnu_cxx::slist::iterator"
171
172     def __init__(self, typename, val):
173         self.val = val
174
175     def to_string(self):
176         nodetype = find_type(self.val.type, '_Node')
177         nodetype = nodetype.strip_typedefs().pointer()
178         return self.val['_M_node'].cast(nodetype).dereference()['_M_data']
179
180 class StdVectorPrinter:
181     "Print a std::vector"
182
183     class _iterator:
184         def __init__ (self, start, finish, bitvec):
185             self.bitvec = bitvec
186             if bitvec:
187                 self.item   = start['_M_p']
188                 self.so     = start['_M_offset']
189                 self.finish = finish['_M_p']
190                 self.fo     = finish['_M_offset']
191                 itype = self.item.dereference().type
192                 self.isize = 8 * itype.sizeof
193             else:
194                 self.item = start
195                 self.finish = finish
196             self.count = 0
197
198         def __iter__(self):
199             return self
200
201         def next(self):
202             count = self.count
203             self.count = self.count + 1
204             if self.bitvec:
205                 if self.item == self.finish and self.so >= self.fo:
206                     raise StopIteration
207                 elt = self.item.dereference()
208                 if elt & (1 << self.so):
209                     obit = 1
210                 else:
211                     obit = 0
212                 self.so = self.so + 1
213                 if self.so >= self.isize:
214                     self.item = self.item + 1
215                     self.so = 0
216                 return ('[%d]' % count, obit)
217             else:
218                 if self.item == self.finish:
219                     raise StopIteration
220                 elt = self.item.dereference()
221                 self.item = self.item + 1
222                 return ('[%d]' % count, elt)
223
224     def __init__(self, typename, val):
225         self.typename = typename
226         self.val = val
227         self.is_bool = val.type.template_argument(0).code  == gdb.TYPE_CODE_BOOL
228
229     def children(self):
230         return self._iterator(self.val['_M_impl']['_M_start'],
231                               self.val['_M_impl']['_M_finish'],
232                               self.is_bool)
233
234     def to_string(self):
235         start = self.val['_M_impl']['_M_start']
236         finish = self.val['_M_impl']['_M_finish']
237         end = self.val['_M_impl']['_M_end_of_storage']
238         if self.is_bool:
239             start = self.val['_M_impl']['_M_start']['_M_p']
240             so    = self.val['_M_impl']['_M_start']['_M_offset']
241             finish = self.val['_M_impl']['_M_finish']['_M_p']
242             fo     = self.val['_M_impl']['_M_finish']['_M_offset']
243             itype = start.dereference().type
244             bl = 8 * itype.sizeof
245             length   = (bl - so) + bl * ((finish - start) - 1) + fo
246             capacity = bl * (end - start)
247             return ('%s<bool> of length %d, capacity %d'
248                     % (self.typename, int (length), int (capacity)))
249         else:
250             return ('%s of length %d, capacity %d'
251                     % (self.typename, int (finish - start), int (end - start)))
252
253     def display_hint(self):
254         return 'array'
255
256 class StdVectorIteratorPrinter:
257     "Print std::vector::iterator"
258
259     def __init__(self, typename, val):
260         self.val = val
261
262     def to_string(self):
263         return self.val['_M_current'].dereference()
264
265 class StdTuplePrinter:
266     "Print a std::tuple"
267
268     class _iterator:
269         def __init__ (self, head):
270             self.head = head
271
272             # Set the base class as the initial head of the
273             # tuple.
274             nodes = self.head.type.fields ()
275             if len (nodes) == 1:
276                 # Set the actual head to the first pair.
277                 self.head  = self.head.cast (nodes[0].type)
278             elif len (nodes) != 0:
279                 raise ValueError, "Top of tuple tree does not consist of a single node."
280             self.count = 0
281
282         def __iter__ (self):
283             return self
284
285         def next (self):
286             nodes = self.head.type.fields ()
287             # Check for further recursions in the inheritance tree.
288             if len (nodes) == 0:
289                 raise StopIteration
290             # Check that this iteration has an expected structure.
291             if len (nodes) != 2:
292                 raise ValueError, "Cannot parse more than 2 nodes in a tuple tree."
293
294             # - Left node is the next recursion parent.
295             # - Right node is the actual class contained in the tuple.
296
297             # Process right node.
298             impl = self.head.cast (nodes[1].type)
299
300             # Process left node and set it as head.
301             self.head  = self.head.cast (nodes[0].type)
302             self.count = self.count + 1
303
304             # Finally, check the implementation.  If it is
305             # wrapped in _M_head_impl return that, otherwise return
306             # the value "as is".
307             fields = impl.type.fields ()
308             if len (fields) < 1 or fields[0].name != "_M_head_impl":
309                 return ('[%d]' % self.count, impl)
310             else:
311                 return ('[%d]' % self.count, impl['_M_head_impl'])
312
313     def __init__ (self, typename, val):
314         self.typename = typename
315         self.val = val;
316
317     def children (self):
318         return self._iterator (self.val)
319
320     def to_string (self):
321         if len (self.val.type.fields ()) == 0:
322             return 'empty %s' % (self.typename)
323         return '%s containing' % (self.typename)
324
325 class StdStackOrQueuePrinter:
326     "Print a std::stack or std::queue"
327
328     def __init__ (self, typename, val):
329         self.typename = typename
330         self.visualizer = gdb.default_visualizer(val['c'])
331
332     def children (self):
333         return self.visualizer.children()
334
335     def to_string (self):
336         return '%s wrapping: %s' % (self.typename,
337                                     self.visualizer.to_string())
338
339     def display_hint (self):
340         if hasattr (self.visualizer, 'display_hint'):
341             return self.visualizer.display_hint ()
342         return None
343
344 class RbtreeIterator:
345     def __init__(self, rbtree):
346         self.size = rbtree['_M_t']['_M_impl']['_M_node_count']
347         self.node = rbtree['_M_t']['_M_impl']['_M_header']['_M_left']
348         self.count = 0
349
350     def __iter__(self):
351         return self
352
353     def __len__(self):
354         return int (self.size)
355
356     def next(self):
357         if self.count == self.size:
358             raise StopIteration
359         result = self.node
360         self.count = self.count + 1
361         if self.count < self.size:
362             # Compute the next node.
363             node = self.node
364             if node.dereference()['_M_right']:
365                 node = node.dereference()['_M_right']
366                 while node.dereference()['_M_left']:
367                     node = node.dereference()['_M_left']
368             else:
369                 parent = node.dereference()['_M_parent']
370                 while node == parent.dereference()['_M_right']:
371                     node = parent
372                     parent = parent.dereference()['_M_parent']
373                 if node.dereference()['_M_right'] != parent:
374                     node = parent
375             self.node = node
376         return result
377
378 # This is a pretty printer for std::_Rb_tree_iterator (which is
379 # std::map::iterator), and has nothing to do with the RbtreeIterator
380 # class above.
381 class StdRbtreeIteratorPrinter:
382     "Print std::map::iterator"
383
384     def __init__ (self, typename, val):
385         self.val = val
386
387     def to_string (self):
388         typename = str(self.val.type.strip_typedefs()) + '::_Link_type'
389         nodetype = gdb.lookup_type(typename).strip_typedefs()
390         return self.val.cast(nodetype).dereference()['_M_value_field']
391
392 class StdDebugIteratorPrinter:
393     "Print a debug enabled version of an iterator"
394
395     def __init__ (self, typename, val):
396         self.val = val
397
398     # Just strip away the encapsulating __gnu_debug::_Safe_iterator
399     # and return the wrapped iterator value.
400     def to_string (self):
401         itype = self.val.type.template_argument(0)
402         return self.val['_M_current'].cast(itype)
403
404 class StdMapPrinter:
405     "Print a std::map or std::multimap"
406
407     # Turn an RbtreeIterator into a pretty-print iterator.
408     class _iter:
409         def __init__(self, rbiter, type):
410             self.rbiter = rbiter
411             self.count = 0
412             self.type = type
413
414         def __iter__(self):
415             return self
416
417         def next(self):
418             if self.count % 2 == 0:
419                 n = self.rbiter.next()
420                 n = n.cast(self.type).dereference()['_M_value_field']
421                 self.pair = n
422                 item = n['first']
423             else:
424                 item = self.pair['second']
425             result = ('[%d]' % self.count, item)
426             self.count = self.count + 1
427             return result
428
429     def __init__ (self, typename, val):
430         self.typename = typename
431         self.val = val
432
433     def to_string (self):
434         return '%s with %d elements' % (self.typename,
435                                         len (RbtreeIterator (self.val)))
436
437     def children (self):
438         rep_type = find_type(self.val.type, '_Rep_type')
439         node = find_type(rep_type, '_Link_type')
440         node = node.strip_typedefs()
441         return self._iter (RbtreeIterator (self.val), node)
442
443     def display_hint (self):
444         return 'map'
445
446 class StdSetPrinter:
447     "Print a std::set or std::multiset"
448
449     # Turn an RbtreeIterator into a pretty-print iterator.
450     class _iter:
451         def __init__(self, rbiter, type):
452             self.rbiter = rbiter
453             self.count = 0
454             self.type = type
455
456         def __iter__(self):
457             return self
458
459         def next(self):
460             item = self.rbiter.next()
461             item = item.cast(self.type).dereference()['_M_value_field']
462             # FIXME: this is weird ... what to do?
463             # Maybe a 'set' display hint?
464             result = ('[%d]' % self.count, item)
465             self.count = self.count + 1
466             return result
467
468     def __init__ (self, typename, val):
469         self.typename = typename
470         self.val = val
471
472     def to_string (self):
473         return '%s with %d elements' % (self.typename,
474                                         len (RbtreeIterator (self.val)))
475
476     def children (self):
477         rep_type = find_type(self.val.type, '_Rep_type')
478         node = find_type(rep_type, '_Link_type')
479         node = node.strip_typedefs()
480         return self._iter (RbtreeIterator (self.val), node)
481
482 class StdBitsetPrinter:
483     "Print a std::bitset"
484
485     def __init__(self, typename, val):
486         self.typename = typename
487         self.val = val
488
489     def to_string (self):
490         # If template_argument handled values, we could print the
491         # size.  Or we could use a regexp on the type.
492         return '%s' % (self.typename)
493
494     def children (self):
495         words = self.val['_M_w']
496         wtype = words.type
497
498         # The _M_w member can be either an unsigned long, or an
499         # array.  This depends on the template specialization used.
500         # If it is a single long, convert to a single element list.
501         if wtype.code == gdb.TYPE_CODE_ARRAY:
502             tsize = wtype.target ().sizeof
503         else:
504             words = [words]
505             tsize = wtype.sizeof 
506
507         nwords = wtype.sizeof / tsize
508         result = []
509         byte = 0
510         while byte < nwords:
511             w = words[byte]
512             bit = 0
513             while w != 0:
514                 if (w & 1) != 0:
515                     # Another spot where we could use 'set'?
516                     result.append(('[%d]' % (byte * tsize * 8 + bit), 1))
517                 bit = bit + 1
518                 w = w >> 1
519             byte = byte + 1
520         return result
521
522 class StdDequePrinter:
523     "Print a std::deque"
524
525     class _iter:
526         def __init__(self, node, start, end, last, buffer_size):
527             self.node = node
528             self.p = start
529             self.end = end
530             self.last = last
531             self.buffer_size = buffer_size
532             self.count = 0
533
534         def __iter__(self):
535             return self
536
537         def next(self):
538             if self.p == self.last:
539                 raise StopIteration
540
541             result = ('[%d]' % self.count, self.p.dereference())
542             self.count = self.count + 1
543
544             # Advance the 'cur' pointer.
545             self.p = self.p + 1
546             if self.p == self.end:
547                 # If we got to the end of this bucket, move to the
548                 # next bucket.
549                 self.node = self.node + 1
550                 self.p = self.node[0]
551                 self.end = self.p + self.buffer_size
552
553             return result
554
555     def __init__(self, typename, val):
556         self.typename = typename
557         self.val = val
558         self.elttype = val.type.template_argument(0)
559         size = self.elttype.sizeof
560         if size < 512:
561             self.buffer_size = int (512 / size)
562         else:
563             self.buffer_size = 1
564
565     def to_string(self):
566         start = self.val['_M_impl']['_M_start']
567         end = self.val['_M_impl']['_M_finish']
568
569         delta_n = end['_M_node'] - start['_M_node'] - 1
570         delta_s = start['_M_last'] - start['_M_cur']
571         delta_e = end['_M_cur'] - end['_M_first']
572
573         size = self.buffer_size * delta_n + delta_s + delta_e
574
575         return '%s with %d elements' % (self.typename, long (size))
576
577     def children(self):
578         start = self.val['_M_impl']['_M_start']
579         end = self.val['_M_impl']['_M_finish']
580         return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
581                           end['_M_cur'], self.buffer_size)
582
583     def display_hint (self):
584         return 'array'
585
586 class StdDequeIteratorPrinter:
587     "Print std::deque::iterator"
588
589     def __init__(self, typename, val):
590         self.val = val
591
592     def to_string(self):
593         return self.val['_M_cur'].dereference()
594
595 class StdStringPrinter:
596     "Print a std::basic_string of some kind"
597
598     def __init__(self, typename, val):
599         self.val = val
600
601     def to_string(self):
602         # Make sure &string works, too.
603         type = self.val.type
604         if type.code == gdb.TYPE_CODE_REF:
605             type = type.target ()
606
607         # Calculate the length of the string so that to_string returns
608         # the string according to length, not according to first null
609         # encountered.
610         ptr = self.val ['_M_dataplus']['_M_p']
611         realtype = type.unqualified ().strip_typedefs ()
612         reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
613         header = ptr.cast(reptype) - 1
614         len = header.dereference ()['_M_length']
615         if hasattr(ptr, "lazy_string"):
616             return ptr.lazy_string (length = len)
617         return ptr.string (length = len)
618
619     def display_hint (self):
620         return 'string'
621
622 class Tr1HashtableIterator:
623     def __init__ (self, hash):
624         self.node = hash['_M_bbegin']['_M_node']['_M_nxt']
625         self.node_type = find_type(hash.type, '__node_type').pointer()
626
627     def __iter__ (self):
628         return self
629
630     def next (self):
631         if self.node == 0:
632             raise StopIteration
633         node = self.node.cast(self.node_type)
634         result = node.dereference()['_M_v']
635         self.node = node.dereference()['_M_nxt']
636         return result
637
638 class Tr1UnorderedSetPrinter:
639     "Print a tr1::unordered_set"
640
641     def __init__ (self, typename, val):
642         self.typename = typename
643         self.val = val
644
645     def hashtable (self):
646         if self.typename.startswith('std::tr1'):
647             return self.val
648         return self.val['_M_h']
649
650     def to_string (self):
651         return '%s with %d elements' % (self.typename, self.hashtable()['_M_element_count'])
652
653     @staticmethod
654     def format_count (i):
655         return '[%d]' % i
656
657     def children (self):
658         counter = itertools.imap (self.format_count, itertools.count())
659         return itertools.izip (counter, Tr1HashtableIterator (self.hashtable()))
660
661 class Tr1UnorderedMapPrinter:
662     "Print a tr1::unordered_map"
663
664     def __init__ (self, typename, val):
665         self.typename = typename
666         self.val = val
667
668     def hashtable (self):
669         if self.typename.startswith('std::tr1'):
670             return self.val
671         return self.val['_M_h']
672
673     def to_string (self):
674         return '%s with %d elements' % (self.typename, self.hashtable()['_M_element_count'])
675
676     @staticmethod
677     def flatten (list):
678         for elt in list:
679             for i in elt:
680                 yield i
681
682     @staticmethod
683     def format_one (elt):
684         return (elt['first'], elt['second'])
685
686     @staticmethod
687     def format_count (i):
688         return '[%d]' % i
689
690     def children (self):
691         counter = itertools.imap (self.format_count, itertools.count())
692         # Map over the hash table and flatten the result.
693         data = self.flatten (itertools.imap (self.format_one, Tr1HashtableIterator (self.hashtable())))
694         # Zip the two iterators together.
695         return itertools.izip (counter, data)
696
697     def display_hint (self):
698         return 'map'
699
700 class StdForwardListPrinter:
701     "Print a std::forward_list"
702
703     class _iterator:
704         def __init__(self, nodetype, head):
705             self.nodetype = nodetype
706             self.base = head['_M_next']
707             self.count = 0
708
709         def __iter__(self):
710             return self
711
712         def next(self):
713             if self.base == 0:
714                 raise StopIteration
715             elt = self.base.cast(self.nodetype).dereference()
716             self.base = elt['_M_next']
717             count = self.count
718             self.count = self.count + 1
719             valptr = elt['_M_storage'].address
720             valptr = valptr.cast(elt.type.template_argument(0).pointer())
721             return ('[%d]' % count, valptr.dereference())
722
723     def __init__(self, typename, val):
724         self.val = val
725         self.typename = typename
726
727     def children(self):
728         nodetype = find_type(self.val.type, '_Node')
729         nodetype = nodetype.strip_typedefs().pointer()
730         return self._iterator(nodetype, self.val['_M_impl']['_M_head'])
731
732     def to_string(self):
733         if self.val['_M_impl']['_M_head']['_M_next'] == 0:
734             return 'empty %s' % (self.typename)
735         return '%s' % (self.typename)
736
737
738 # A "regular expression" printer which conforms to the
739 # "SubPrettyPrinter" protocol from gdb.printing.
740 class RxPrinter(object):
741     def __init__(self, name, function):
742         super(RxPrinter, self).__init__()
743         self.name = name
744         self.function = function
745         self.enabled = True
746
747     def invoke(self, value):
748         if not self.enabled:
749             return None
750         return self.function(self.name, value)
751
752 # A pretty-printer that conforms to the "PrettyPrinter" protocol from
753 # gdb.printing.  It can also be used directly as an old-style printer.
754 class Printer(object):
755     def __init__(self, name):
756         super(Printer, self).__init__()
757         self.name = name
758         self.subprinters = []
759         self.lookup = {}
760         self.enabled = True
761         self.compiled_rx = re.compile('^([a-zA-Z0-9_:]+)<.*>$')
762
763     def add(self, name, function):
764         # A small sanity check.
765         # FIXME
766         if not self.compiled_rx.match(name + '<>'):
767             raise ValueError, 'libstdc++ programming error: "%s" does not match' % name
768         printer = RxPrinter(name, function)
769         self.subprinters.append(printer)
770         self.lookup[name] = printer
771
772     # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
773     def add_version(self, base, name, function):
774         self.add(base + name, function)
775         self.add(base + '__7::' + name, function)
776
777     # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
778     def add_container(self, base, name, function):
779         self.add_version(base, name, function)
780         self.add_version(base + '__cxx1998::', name, function)
781
782     @staticmethod
783     def get_basic_type(type):
784         # If it points to a reference, get the reference.
785         if type.code == gdb.TYPE_CODE_REF:
786             type = type.target ()
787
788         # Get the unqualified type, stripped of typedefs.
789         type = type.unqualified ().strip_typedefs ()
790
791         return type.tag
792
793     def __call__(self, val):
794         typename = self.get_basic_type(val.type)
795         if not typename:
796             return None
797
798         # All the types we match are template types, so we can use a
799         # dictionary.
800         match = self.compiled_rx.match(typename)
801         if not match:
802             return None
803
804         basename = match.group(1)
805         if basename in self.lookup:
806             return self.lookup[basename].invoke(val)
807
808         # Cannot find a pretty printer.  Return None.
809         return None
810
811 libstdcxx_printer = None
812
813 class FilteringTypePrinter(object):
814     def __init__(self, match, name):
815         self.match = match
816         self.name = name
817         self.enabled = True
818
819     class _recognizer(object):
820         def __init__(self, match, name):
821             self.match = match
822             self.name = name
823             self.type_obj = None
824
825         def recognize(self, type_obj):
826             if type_obj.tag is None:
827                 return None
828
829             if self.type_obj is None:
830                 if not self.match in type_obj.tag:
831                     # Filter didn't match.
832                     return None
833                 try:
834                     self.type_obj = gdb.lookup_type(self.name).strip_typedefs()
835                 except:
836                     pass
837             if self.type_obj == type_obj:
838                 return self.name
839             return None
840
841     def instantiate(self):
842         return self._recognizer(self.match, self.name)
843
844 def add_one_type_printer(obj, match, name):
845     printer = FilteringTypePrinter(match, 'std::' + name)
846     gdb.types.register_type_printer(obj, printer)
847
848 def register_type_printers(obj):
849     global _use_type_printing
850
851     if not _use_type_printing:
852         return
853
854     for pfx in ('', 'w'):
855         add_one_type_printer(obj, 'basic_string', pfx + 'string')
856         add_one_type_printer(obj, 'basic_ios', pfx + 'ios')
857         add_one_type_printer(obj, 'basic_streambuf', pfx + 'streambuf')
858         add_one_type_printer(obj, 'basic_istream', pfx + 'istream')
859         add_one_type_printer(obj, 'basic_ostream', pfx + 'ostream')
860         add_one_type_printer(obj, 'basic_iostream', pfx + 'iostream')
861         add_one_type_printer(obj, 'basic_stringbuf', pfx + 'stringbuf')
862         add_one_type_printer(obj, 'basic_istringstream',
863                                  pfx + 'istringstream')
864         add_one_type_printer(obj, 'basic_ostringstream',
865                                  pfx + 'ostringstream')
866         add_one_type_printer(obj, 'basic_stringstream',
867                                  pfx + 'stringstream')
868         add_one_type_printer(obj, 'basic_filebuf', pfx + 'filebuf')
869         add_one_type_printer(obj, 'basic_ifstream', pfx + 'ifstream')
870         add_one_type_printer(obj, 'basic_ofstream', pfx + 'ofstream')
871         add_one_type_printer(obj, 'basic_fstream', pfx + 'fstream')
872         add_one_type_printer(obj, 'basic_regex', pfx + 'regex')
873         add_one_type_printer(obj, 'sub_match', pfx + 'csub_match')
874         add_one_type_printer(obj, 'sub_match', pfx + 'ssub_match')
875         add_one_type_printer(obj, 'match_results', pfx + 'cmatch')
876         add_one_type_printer(obj, 'match_results', pfx + 'smatch')
877         add_one_type_printer(obj, 'regex_iterator', pfx + 'cregex_iterator')
878         add_one_type_printer(obj, 'regex_iterator', pfx + 'sregex_iterator')
879         add_one_type_printer(obj, 'regex_token_iterator',
880                                  pfx + 'cregex_token_iterator')
881         add_one_type_printer(obj, 'regex_token_iterator',
882                                  pfx + 'sregex_token_iterator')
883
884     # Note that we can't have a printer for std::wstreampos, because
885     # it shares the same underlying type as std::streampos.
886     add_one_type_printer(obj, 'fpos', 'streampos')
887     add_one_type_printer(obj, 'basic_string', 'u16string')
888     add_one_type_printer(obj, 'basic_string', 'u32string')
889
890     for dur in ('nanoseconds', 'microseconds', 'milliseconds',
891                 'seconds', 'minutes', 'hours'):
892         add_one_type_printer(obj, 'duration', dur)
893
894     add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand0')
895     add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand')
896     add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937')
897     add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937_64')
898     add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux24_base')
899     add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux48_base')
900     add_one_type_printer(obj, 'discard_block_engine', 'ranlux24')
901     add_one_type_printer(obj, 'discard_block_engine', 'ranlux48')
902     add_one_type_printer(obj, 'shuffle_order_engine', 'knuth_b')
903
904 def register_libstdcxx_printers (obj):
905     "Register libstdc++ pretty-printers with objfile Obj."
906
907     global _use_gdb_pp
908     global libstdcxx_printer
909
910     if _use_gdb_pp:
911         gdb.printing.register_pretty_printer(obj, libstdcxx_printer)
912     else:
913         if obj is None:
914             obj = gdb
915         obj.pretty_printers.append(libstdcxx_printer)
916
917     register_type_printers(obj)
918
919 def build_libstdcxx_dictionary ():
920     global libstdcxx_printer
921
922     libstdcxx_printer = Printer("libstdc++-v6")
923
924     # For _GLIBCXX_BEGIN_NAMESPACE_VERSION.
925     vers = '(__7::)?'
926     # For _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
927     container = '(__cxx1998::' + vers + ')?'
928
929     # libstdc++ objects requiring pretty-printing.
930     # In order from:
931     # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
932     libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
933     libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
934     libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
935     libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
936     libstdcxx_printer.add_container('std::', 'map', StdMapPrinter)
937     libstdcxx_printer.add_container('std::', 'multimap', StdMapPrinter)
938     libstdcxx_printer.add_container('std::', 'multiset', StdSetPrinter)
939     libstdcxx_printer.add_version('std::', 'priority_queue',
940                                   StdStackOrQueuePrinter)
941     libstdcxx_printer.add_version('std::', 'queue', StdStackOrQueuePrinter)
942     libstdcxx_printer.add_version('std::', 'tuple', StdTuplePrinter)
943     libstdcxx_printer.add_container('std::', 'set', StdSetPrinter)
944     libstdcxx_printer.add_version('std::', 'stack', StdStackOrQueuePrinter)
945     libstdcxx_printer.add_version('std::', 'unique_ptr', UniquePointerPrinter)
946     libstdcxx_printer.add_container('std::', 'vector', StdVectorPrinter)
947     # vector<bool>
948
949     # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
950     libstdcxx_printer.add('std::__debug::bitset', StdBitsetPrinter)
951     libstdcxx_printer.add('std::__debug::deque', StdDequePrinter)
952     libstdcxx_printer.add('std::__debug::list', StdListPrinter)
953     libstdcxx_printer.add('std::__debug::map', StdMapPrinter)
954     libstdcxx_printer.add('std::__debug::multimap', StdMapPrinter)
955     libstdcxx_printer.add('std::__debug::multiset', StdSetPrinter)
956     libstdcxx_printer.add('std::__debug::priority_queue',
957                           StdStackOrQueuePrinter)
958     libstdcxx_printer.add('std::__debug::queue', StdStackOrQueuePrinter)
959     libstdcxx_printer.add('std::__debug::set', StdSetPrinter)
960     libstdcxx_printer.add('std::__debug::stack', StdStackOrQueuePrinter)
961     libstdcxx_printer.add('std::__debug::unique_ptr', UniquePointerPrinter)
962     libstdcxx_printer.add('std::__debug::vector', StdVectorPrinter)
963
964     # These are the TR1 and C++0x printers.
965     # For array - the default GDB pretty-printer seems reasonable.
966     libstdcxx_printer.add_version('std::', 'shared_ptr', SharedPointerPrinter)
967     libstdcxx_printer.add_version('std::', 'weak_ptr', SharedPointerPrinter)
968     libstdcxx_printer.add_container('std::', 'unordered_map',
969                                     Tr1UnorderedMapPrinter)
970     libstdcxx_printer.add_container('std::', 'unordered_set',
971                                     Tr1UnorderedSetPrinter)
972     libstdcxx_printer.add_container('std::', 'unordered_multimap',
973                                     Tr1UnorderedMapPrinter)
974     libstdcxx_printer.add_container('std::', 'unordered_multiset',
975                                     Tr1UnorderedSetPrinter)
976     libstdcxx_printer.add_container('std::', 'forward_list',
977                                     StdForwardListPrinter)
978
979     libstdcxx_printer.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter)
980     libstdcxx_printer.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter)
981     libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
982                                   Tr1UnorderedMapPrinter)
983     libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
984                                   Tr1UnorderedSetPrinter)
985     libstdcxx_printer.add_version('std::tr1::', 'unordered_multimap',
986                                   Tr1UnorderedMapPrinter)
987     libstdcxx_printer.add_version('std::tr1::', 'unordered_multiset',
988                                   Tr1UnorderedSetPrinter)
989
990     # These are the C++0x printer registrations for -D_GLIBCXX_DEBUG cases.
991     # The tr1 namespace printers do not seem to have any debug
992     # equivalents, so do no register them.
993     libstdcxx_printer.add('std::__debug::unordered_map',
994                           Tr1UnorderedMapPrinter)
995     libstdcxx_printer.add('std::__debug::unordered_set',
996                           Tr1UnorderedSetPrinter)
997     libstdcxx_printer.add('std::__debug::unordered_multimap',
998                           Tr1UnorderedMapPrinter)
999     libstdcxx_printer.add('std::__debug::unordered_multiset',
1000                           Tr1UnorderedSetPrinter)
1001     libstdcxx_printer.add('std::__debug::forward_list',
1002                           StdForwardListPrinter)
1003
1004
1005     # Extensions.
1006     libstdcxx_printer.add_version('__gnu_cxx::', 'slist', StdSlistPrinter)
1007
1008     if True:
1009         # These shouldn't be necessary, if GDB "print *i" worked.
1010         # But it often doesn't, so here they are.
1011         libstdcxx_printer.add_container('std::', '_List_iterator',
1012                                         StdListIteratorPrinter)
1013         libstdcxx_printer.add_container('std::', '_List_const_iterator',
1014                                         StdListIteratorPrinter)
1015         libstdcxx_printer.add_version('std::', '_Rb_tree_iterator',
1016                                       StdRbtreeIteratorPrinter)
1017         libstdcxx_printer.add_version('std::', '_Rb_tree_const_iterator',
1018                                       StdRbtreeIteratorPrinter)
1019         libstdcxx_printer.add_container('std::', '_Deque_iterator',
1020                                         StdDequeIteratorPrinter)
1021         libstdcxx_printer.add_container('std::', '_Deque_const_iterator',
1022                                         StdDequeIteratorPrinter)
1023         libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
1024                                       StdVectorIteratorPrinter)
1025         libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
1026                                       StdSlistIteratorPrinter)
1027
1028         # Debug (compiled with -D_GLIBCXX_DEBUG) printer
1029         # registrations.  The Rb_tree debug iterator when unwrapped
1030         # from the encapsulating __gnu_debug::_Safe_iterator does not
1031         # have the __norm namespace. Just use the existing printer
1032         # registration for that.
1033         libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
1034                               StdDebugIteratorPrinter)
1035         libstdcxx_printer.add('std::__norm::_List_iterator',
1036                               StdListIteratorPrinter)
1037         libstdcxx_printer.add('std::__norm::_List_const_iterator',
1038                               StdListIteratorPrinter)
1039         libstdcxx_printer.add('std::__norm::_Deque_const_iterator',
1040                               StdDequeIteratorPrinter)
1041         libstdcxx_printer.add('std::__norm::_Deque_iterator',
1042                               StdDequeIteratorPrinter)
1043
1044 build_libstdcxx_dictionary ()