xref: /netbsd-src/external/gpl3/gcc.old/dist/libstdc++-v3/python/libstdcxx/v6/printers.py (revision c9496f6b604074a9451a67df576a5b423068e71e)
1# Pretty-printers for libstdc++.
2
3# Copyright (C) 2008-2015 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
18import gdb
19import itertools
20import re
21import sys
22
23### Python 2 + Python 3 compatibility code
24
25# Resources about compatibility:
26#
27#  * <http://pythonhosted.org/six/>: Documentation of the "six" module
28
29# FIXME: The handling of e.g. std::basic_string (at least on char)
30# probably needs updating to work with Python 3's new string rules.
31#
32# In particular, Python 3 has a separate type (called byte) for
33# bytestrings, and a special b"" syntax for the byte literals; the old
34# str() type has been redefined to always store Unicode text.
35#
36# We probably can't do much about this until this GDB PR is addressed:
37# <https://sourceware.org/bugzilla/show_bug.cgi?id=17138>
38
39if sys.version_info[0] > 2:
40    ### Python 3 stuff
41    Iterator = object
42    # Python 3 folds these into the normal functions.
43    imap = map
44    izip = zip
45    # Also, int subsumes long
46    long = int
47else:
48    ### Python 2 stuff
49    class Iterator:
50        """Compatibility mixin for iterators
51
52        Instead of writing next() methods for iterators, write
53        __next__() methods and use this mixin to make them work in
54        Python 2 as well as Python 3.
55
56        Idea stolen from the "six" documentation:
57        <http://pythonhosted.org/six/#six.Iterator>
58        """
59
60        def next(self):
61            return self.__next__()
62
63    # In Python 2, we still need these from itertools
64    from itertools import imap, izip
65
66# Try to use the new-style pretty-printing if available.
67_use_gdb_pp = True
68try:
69    import gdb.printing
70except ImportError:
71    _use_gdb_pp = False
72
73# Try to install type-printers.
74_use_type_printing = False
75try:
76    import gdb.types
77    if hasattr(gdb.types, 'TypePrinter'):
78        _use_type_printing = True
79except ImportError:
80    pass
81
82# Starting with the type ORIG, search for the member type NAME.  This
83# handles searching upward through superclasses.  This is needed to
84# work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
85def find_type(orig, name):
86    typ = orig.strip_typedefs()
87    while True:
88        # Strip cv-qualifiers.  PR 67440.
89        search = '%s::%s' % (typ.unqualified(), name)
90        try:
91            return gdb.lookup_type(search)
92        except RuntimeError:
93            pass
94        # The type was not found, so try the superclass.  We only need
95        # to check the first superclass, so we don't bother with
96        # anything fancier here.
97        field = typ.fields()[0]
98        if not field.is_base_class:
99            raise ValueError("Cannot find type %s::%s" % (str(orig), name))
100        typ = field.type
101
102class SharedPointerPrinter:
103    "Print a shared_ptr or weak_ptr"
104
105    def __init__ (self, typename, val):
106        self.typename = typename
107        self.val = val
108
109    def to_string (self):
110        state = 'empty'
111        refcounts = self.val['_M_refcount']['_M_pi']
112        if refcounts != 0:
113            usecount = refcounts['_M_use_count']
114            weakcount = refcounts['_M_weak_count']
115            if usecount == 0:
116                state = 'expired, weak %d' % weakcount
117            else:
118                state = 'count %d, weak %d' % (usecount, weakcount - 1)
119        return '%s (%s) %s' % (self.typename, state, self.val['_M_ptr'])
120
121class UniquePointerPrinter:
122    "Print a unique_ptr"
123
124    def __init__ (self, typename, val):
125        self.val = val
126
127    def to_string (self):
128        v = self.val['_M_t']['_M_head_impl']
129        return ('std::unique_ptr<%s> containing %s' % (str(v.type.target()),
130                                                       str(v)))
131
132class StdListPrinter:
133    "Print a std::list"
134
135    class _iterator(Iterator):
136        def __init__(self, nodetype, head):
137            self.nodetype = nodetype
138            self.base = head['_M_next']
139            self.head = head.address
140            self.count = 0
141
142        def __iter__(self):
143            return self
144
145        def __next__(self):
146            if self.base == self.head:
147                raise StopIteration
148            elt = self.base.cast(self.nodetype).dereference()
149            self.base = elt['_M_next']
150            count = self.count
151            self.count = self.count + 1
152            return ('[%d]' % count, elt['_M_data'])
153
154    def __init__(self, typename, val):
155        self.typename = typename
156        self.val = val
157
158    def children(self):
159        nodetype = find_type(self.val.type, '_Node')
160        nodetype = nodetype.strip_typedefs().pointer()
161        return self._iterator(nodetype, self.val['_M_impl']['_M_node'])
162
163    def to_string(self):
164        if self.val['_M_impl']['_M_node'].address == self.val['_M_impl']['_M_node']['_M_next']:
165            return 'empty %s' % (self.typename)
166        return '%s' % (self.typename)
167
168class StdListIteratorPrinter:
169    "Print std::list::iterator"
170
171    def __init__(self, typename, val):
172        self.val = val
173        self.typename = typename
174
175    def to_string(self):
176        if not self.val['_M_node']:
177            return 'non-dereferenceable iterator for std::list'
178        nodetype = find_type(self.val.type, '_Node')
179        nodetype = nodetype.strip_typedefs().pointer()
180        return str(self.val['_M_node'].cast(nodetype).dereference()['_M_data'])
181
182class StdSlistPrinter:
183    "Print a __gnu_cxx::slist"
184
185    class _iterator(Iterator):
186        def __init__(self, nodetype, head):
187            self.nodetype = nodetype
188            self.base = head['_M_head']['_M_next']
189            self.count = 0
190
191        def __iter__(self):
192            return self
193
194        def __next__(self):
195            if self.base == 0:
196                raise StopIteration
197            elt = self.base.cast(self.nodetype).dereference()
198            self.base = elt['_M_next']
199            count = self.count
200            self.count = self.count + 1
201            return ('[%d]' % count, elt['_M_data'])
202
203    def __init__(self, typename, val):
204        self.val = val
205
206    def children(self):
207        nodetype = find_type(self.val.type, '_Node')
208        nodetype = nodetype.strip_typedefs().pointer()
209        return self._iterator(nodetype, self.val)
210
211    def to_string(self):
212        if self.val['_M_head']['_M_next'] == 0:
213            return 'empty __gnu_cxx::slist'
214        return '__gnu_cxx::slist'
215
216class StdSlistIteratorPrinter:
217    "Print __gnu_cxx::slist::iterator"
218
219    def __init__(self, typename, val):
220        self.val = val
221
222    def to_string(self):
223        if not self.val['_M_node']:
224            return 'non-dereferenceable iterator for __gnu_cxx::slist'
225        nodetype = find_type(self.val.type, '_Node')
226        nodetype = nodetype.strip_typedefs().pointer()
227        return str(self.val['_M_node'].cast(nodetype).dereference()['_M_data'])
228
229class StdVectorPrinter:
230    "Print a std::vector"
231
232    class _iterator(Iterator):
233        def __init__ (self, start, finish, bitvec):
234            self.bitvec = bitvec
235            if bitvec:
236                self.item   = start['_M_p']
237                self.so     = start['_M_offset']
238                self.finish = finish['_M_p']
239                self.fo     = finish['_M_offset']
240                itype = self.item.dereference().type
241                self.isize = 8 * itype.sizeof
242            else:
243                self.item = start
244                self.finish = finish
245            self.count = 0
246
247        def __iter__(self):
248            return self
249
250        def __next__(self):
251            count = self.count
252            self.count = self.count + 1
253            if self.bitvec:
254                if self.item == self.finish and self.so >= self.fo:
255                    raise StopIteration
256                elt = self.item.dereference()
257                if elt & (1 << self.so):
258                    obit = 1
259                else:
260                    obit = 0
261                self.so = self.so + 1
262                if self.so >= self.isize:
263                    self.item = self.item + 1
264                    self.so = 0
265                return ('[%d]' % count, obit)
266            else:
267                if self.item == self.finish:
268                    raise StopIteration
269                elt = self.item.dereference()
270                self.item = self.item + 1
271                return ('[%d]' % count, elt)
272
273    def __init__(self, typename, val):
274        self.typename = typename
275        self.val = val
276        self.is_bool = val.type.template_argument(0).code  == gdb.TYPE_CODE_BOOL
277
278    def children(self):
279        return self._iterator(self.val['_M_impl']['_M_start'],
280                              self.val['_M_impl']['_M_finish'],
281                              self.is_bool)
282
283    def to_string(self):
284        start = self.val['_M_impl']['_M_start']
285        finish = self.val['_M_impl']['_M_finish']
286        end = self.val['_M_impl']['_M_end_of_storage']
287        if self.is_bool:
288            start = self.val['_M_impl']['_M_start']['_M_p']
289            so    = self.val['_M_impl']['_M_start']['_M_offset']
290            finish = self.val['_M_impl']['_M_finish']['_M_p']
291            fo     = self.val['_M_impl']['_M_finish']['_M_offset']
292            itype = start.dereference().type
293            bl = 8 * itype.sizeof
294            length   = (bl - so) + bl * ((finish - start) - 1) + fo
295            capacity = bl * (end - start)
296            return ('%s<bool> of length %d, capacity %d'
297                    % (self.typename, int (length), int (capacity)))
298        else:
299            return ('%s of length %d, capacity %d'
300                    % (self.typename, int (finish - start), int (end - start)))
301
302    def display_hint(self):
303        return 'array'
304
305class StdVectorIteratorPrinter:
306    "Print std::vector::iterator"
307
308    def __init__(self, typename, val):
309        self.val = val
310
311    def to_string(self):
312        if not self.val['_M_current']:
313            return 'non-dereferenceable iterator for std::vector'
314        return str(self.val['_M_current'].dereference())
315
316class StdTuplePrinter:
317    "Print a std::tuple"
318
319    class _iterator(Iterator):
320        def __init__ (self, head):
321            self.head = head
322
323            # Set the base class as the initial head of the
324            # tuple.
325            nodes = self.head.type.fields ()
326            if len (nodes) == 1:
327                # Set the actual head to the first pair.
328                self.head  = self.head.cast (nodes[0].type)
329            elif len (nodes) != 0:
330                raise ValueError("Top of tuple tree does not consist of a single node.")
331            self.count = 0
332
333        def __iter__ (self):
334            return self
335
336        def __next__ (self):
337            # Check for further recursions in the inheritance tree.
338            # For a GCC 5+ tuple self.head is None after visiting all nodes:
339            if not self.head:
340                raise StopIteration
341            nodes = self.head.type.fields ()
342            # For a GCC 4.x tuple there is a final node with no fields:
343            if len (nodes) == 0:
344                raise StopIteration
345            # Check that this iteration has an expected structure.
346            if len (nodes) > 2:
347                raise ValueError("Cannot parse more than 2 nodes in a tuple tree.")
348
349            if len (nodes) == 1:
350                # This is the last node of a GCC 5+ std::tuple.
351                impl = self.head.cast (nodes[0].type)
352                self.head = None
353            else:
354                # Either a node before the last node, or the last node of
355                # a GCC 4.x tuple (which has an empty parent).
356
357                # - Left node is the next recursion parent.
358                # - Right node is the actual class contained in the tuple.
359
360                # Process right node.
361                impl = self.head.cast (nodes[1].type)
362
363                # Process left node and set it as head.
364                self.head  = self.head.cast (nodes[0].type)
365
366            self.count = self.count + 1
367
368            # Finally, check the implementation.  If it is
369            # wrapped in _M_head_impl return that, otherwise return
370            # the value "as is".
371            fields = impl.type.fields ()
372            if len (fields) < 1 or fields[0].name != "_M_head_impl":
373                return ('[%d]' % self.count, impl)
374            else:
375                return ('[%d]' % self.count, impl['_M_head_impl'])
376
377    def __init__ (self, typename, val):
378        self.typename = typename
379        self.val = val;
380
381    def children (self):
382        return self._iterator (self.val)
383
384    def to_string (self):
385        if len (self.val.type.fields ()) == 0:
386            return 'empty %s' % (self.typename)
387        return '%s containing' % (self.typename)
388
389class StdStackOrQueuePrinter:
390    "Print a std::stack or std::queue"
391
392    def __init__ (self, typename, val):
393        self.typename = typename
394        self.visualizer = gdb.default_visualizer(val['c'])
395
396    def children (self):
397        return self.visualizer.children()
398
399    def to_string (self):
400        return '%s wrapping: %s' % (self.typename,
401                                    self.visualizer.to_string())
402
403    def display_hint (self):
404        if hasattr (self.visualizer, 'display_hint'):
405            return self.visualizer.display_hint ()
406        return None
407
408class RbtreeIterator(Iterator):
409    def __init__(self, rbtree):
410        self.size = rbtree['_M_t']['_M_impl']['_M_node_count']
411        self.node = rbtree['_M_t']['_M_impl']['_M_header']['_M_left']
412        self.count = 0
413
414    def __iter__(self):
415        return self
416
417    def __len__(self):
418        return int (self.size)
419
420    def __next__(self):
421        if self.count == self.size:
422            raise StopIteration
423        result = self.node
424        self.count = self.count + 1
425        if self.count < self.size:
426            # Compute the next node.
427            node = self.node
428            if node.dereference()['_M_right']:
429                node = node.dereference()['_M_right']
430                while node.dereference()['_M_left']:
431                    node = node.dereference()['_M_left']
432            else:
433                parent = node.dereference()['_M_parent']
434                while node == parent.dereference()['_M_right']:
435                    node = parent
436                    parent = parent.dereference()['_M_parent']
437                if node.dereference()['_M_right'] != parent:
438                    node = parent
439            self.node = node
440        return result
441
442def get_value_from_Rb_tree_node(node):
443    """Returns the value held in an _Rb_tree_node<_Val>"""
444    try:
445        member = node.type.fields()[1].name
446        if member == '_M_value_field':
447            # C++03 implementation, node contains the value as a member
448            return node['_M_value_field']
449        elif member == '_M_storage':
450            # C++11 implementation, node stores value in __aligned_buffer
451            p = node['_M_storage']['_M_storage'].address
452            p = p.cast(node.type.template_argument(0).pointer())
453            return p.dereference()
454    except:
455        pass
456    raise ValueError("Unsupported implementation for %s" % str(node.type))
457
458# This is a pretty printer for std::_Rb_tree_iterator (which is
459# std::map::iterator), and has nothing to do with the RbtreeIterator
460# class above.
461class StdRbtreeIteratorPrinter:
462    "Print std::map::iterator"
463
464    def __init__ (self, typename, val):
465        self.val = val
466        valtype = self.val.type.template_argument(0).strip_typedefs()
467        nodetype = gdb.lookup_type('std::_Rb_tree_node<' + str(valtype) + '>')
468        self.link_type = nodetype.strip_typedefs().pointer()
469
470    def to_string (self):
471        if not self.val['_M_node']:
472            return 'non-dereferenceable iterator for associative container'
473        node = self.val['_M_node'].cast(self.link_type).dereference()
474        return str(get_value_from_Rb_tree_node(node))
475
476class StdDebugIteratorPrinter:
477    "Print a debug enabled version of an iterator"
478
479    def __init__ (self, typename, val):
480        self.val = val
481
482    # Just strip away the encapsulating __gnu_debug::_Safe_iterator
483    # and return the wrapped iterator value.
484    def to_string (self):
485        itype = self.val.type.template_argument(0)
486        return str(self.val.cast(itype))
487
488class StdMapPrinter:
489    "Print a std::map or std::multimap"
490
491    # Turn an RbtreeIterator into a pretty-print iterator.
492    class _iter(Iterator):
493        def __init__(self, rbiter, type):
494            self.rbiter = rbiter
495            self.count = 0
496            self.type = type
497
498        def __iter__(self):
499            return self
500
501        def __next__(self):
502            if self.count % 2 == 0:
503                n = next(self.rbiter)
504                n = n.cast(self.type).dereference()
505                n = get_value_from_Rb_tree_node(n)
506                self.pair = n
507                item = n['first']
508            else:
509                item = self.pair['second']
510            result = ('[%d]' % self.count, item)
511            self.count = self.count + 1
512            return result
513
514    def __init__ (self, typename, val):
515        self.typename = typename
516        self.val = val
517
518    def to_string (self):
519        return '%s with %d elements' % (self.typename,
520                                        len (RbtreeIterator (self.val)))
521
522    def children (self):
523        rep_type = find_type(self.val.type, '_Rep_type')
524        node = find_type(rep_type, '_Link_type')
525        node = node.strip_typedefs()
526        return self._iter (RbtreeIterator (self.val), node)
527
528    def display_hint (self):
529        return 'map'
530
531class StdSetPrinter:
532    "Print a std::set or std::multiset"
533
534    # Turn an RbtreeIterator into a pretty-print iterator.
535    class _iter(Iterator):
536        def __init__(self, rbiter, type):
537            self.rbiter = rbiter
538            self.count = 0
539            self.type = type
540
541        def __iter__(self):
542            return self
543
544        def __next__(self):
545            item = next(self.rbiter)
546            item = item.cast(self.type).dereference()
547            item = get_value_from_Rb_tree_node(item)
548            # FIXME: this is weird ... what to do?
549            # Maybe a 'set' display hint?
550            result = ('[%d]' % self.count, item)
551            self.count = self.count + 1
552            return result
553
554    def __init__ (self, typename, val):
555        self.typename = typename
556        self.val = val
557
558    def to_string (self):
559        return '%s with %d elements' % (self.typename,
560                                        len (RbtreeIterator (self.val)))
561
562    def children (self):
563        rep_type = find_type(self.val.type, '_Rep_type')
564        node = find_type(rep_type, '_Link_type')
565        node = node.strip_typedefs()
566        return self._iter (RbtreeIterator (self.val), node)
567
568class StdBitsetPrinter:
569    "Print a std::bitset"
570
571    def __init__(self, typename, val):
572        self.typename = typename
573        self.val = val
574
575    def to_string (self):
576        # If template_argument handled values, we could print the
577        # size.  Or we could use a regexp on the type.
578        return '%s' % (self.typename)
579
580    def children (self):
581        words = self.val['_M_w']
582        wtype = words.type
583
584        # The _M_w member can be either an unsigned long, or an
585        # array.  This depends on the template specialization used.
586        # If it is a single long, convert to a single element list.
587        if wtype.code == gdb.TYPE_CODE_ARRAY:
588            tsize = wtype.target ().sizeof
589        else:
590            words = [words]
591            tsize = wtype.sizeof
592
593        nwords = wtype.sizeof / tsize
594        result = []
595        byte = 0
596        while byte < nwords:
597            w = words[byte]
598            bit = 0
599            while w != 0:
600                if (w & 1) != 0:
601                    # Another spot where we could use 'set'?
602                    result.append(('[%d]' % (byte * tsize * 8 + bit), 1))
603                bit = bit + 1
604                w = w >> 1
605            byte = byte + 1
606        return result
607
608class StdDequePrinter:
609    "Print a std::deque"
610
611    class _iter(Iterator):
612        def __init__(self, node, start, end, last, buffer_size):
613            self.node = node
614            self.p = start
615            self.end = end
616            self.last = last
617            self.buffer_size = buffer_size
618            self.count = 0
619
620        def __iter__(self):
621            return self
622
623        def __next__(self):
624            if self.p == self.last:
625                raise StopIteration
626
627            result = ('[%d]' % self.count, self.p.dereference())
628            self.count = self.count + 1
629
630            # Advance the 'cur' pointer.
631            self.p = self.p + 1
632            if self.p == self.end:
633                # If we got to the end of this bucket, move to the
634                # next bucket.
635                self.node = self.node + 1
636                self.p = self.node[0]
637                self.end = self.p + self.buffer_size
638
639            return result
640
641    def __init__(self, typename, val):
642        self.typename = typename
643        self.val = val
644        self.elttype = val.type.template_argument(0)
645        size = self.elttype.sizeof
646        if size < 512:
647            self.buffer_size = int (512 / size)
648        else:
649            self.buffer_size = 1
650
651    def to_string(self):
652        start = self.val['_M_impl']['_M_start']
653        end = self.val['_M_impl']['_M_finish']
654
655        delta_n = end['_M_node'] - start['_M_node'] - 1
656        delta_s = start['_M_last'] - start['_M_cur']
657        delta_e = end['_M_cur'] - end['_M_first']
658
659        size = self.buffer_size * delta_n + delta_s + delta_e
660
661        return '%s with %d elements' % (self.typename, long (size))
662
663    def children(self):
664        start = self.val['_M_impl']['_M_start']
665        end = self.val['_M_impl']['_M_finish']
666        return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
667                          end['_M_cur'], self.buffer_size)
668
669    def display_hint (self):
670        return 'array'
671
672class StdDequeIteratorPrinter:
673    "Print std::deque::iterator"
674
675    def __init__(self, typename, val):
676        self.val = val
677
678    def to_string(self):
679        if not self.val['_M_cur']:
680            return 'non-dereferenceable iterator for std::deque'
681        return str(self.val['_M_cur'].dereference())
682
683class StdStringPrinter:
684    "Print a std::basic_string of some kind"
685
686    def __init__(self, typename, val):
687        self.val = val
688        self.new_string = typename.find("::__cxx11::basic_string") != -1
689
690    def to_string(self):
691        # Make sure &string works, too.
692        type = self.val.type
693        if type.code == gdb.TYPE_CODE_REF:
694            type = type.target ()
695
696        # Calculate the length of the string so that to_string returns
697        # the string according to length, not according to first null
698        # encountered.
699        ptr = self.val ['_M_dataplus']['_M_p']
700        if self.new_string:
701            length = self.val['_M_string_length']
702            # https://sourceware.org/bugzilla/show_bug.cgi?id=17728
703            ptr = ptr.cast(ptr.type.strip_typedefs())
704        else:
705            realtype = type.unqualified ().strip_typedefs ()
706            reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
707            header = ptr.cast(reptype) - 1
708            length = header.dereference ()['_M_length']
709        if hasattr(ptr, "lazy_string"):
710            return ptr.lazy_string (length = length)
711        return ptr.string (length = length)
712
713    def display_hint (self):
714        return 'string'
715
716class Tr1HashtableIterator(Iterator):
717    def __init__ (self, hash):
718        self.buckets = hash['_M_buckets']
719        self.bucket = 0
720        self.bucket_count = hash['_M_bucket_count']
721        self.node_type = find_type(hash.type, '_Node').pointer()
722        self.node = 0
723        while self.bucket != self.bucket_count:
724            self.node = self.buckets[self.bucket]
725            if self.node:
726                break
727            self.bucket = self.bucket + 1
728
729    def __iter__ (self):
730        return self
731
732    def __next__ (self):
733        if self.node == 0:
734            raise StopIteration
735        node = self.node.cast(self.node_type)
736        result = node.dereference()['_M_v']
737        self.node = node.dereference()['_M_next'];
738        if self.node == 0:
739            self.bucket = self.bucket + 1
740            while self.bucket != self.bucket_count:
741                self.node = self.buckets[self.bucket]
742                if self.node:
743                    break
744                self.bucket = self.bucket + 1
745        return result
746
747class StdHashtableIterator(Iterator):
748    def __init__(self, hash):
749        self.node = hash['_M_before_begin']['_M_nxt']
750        self.node_type = find_type(hash.type, '__node_type').pointer()
751
752    def __iter__(self):
753        return self
754
755    def __next__(self):
756        if self.node == 0:
757            raise StopIteration
758        elt = self.node.cast(self.node_type).dereference()
759        self.node = elt['_M_nxt']
760        valptr = elt['_M_storage'].address
761        valptr = valptr.cast(elt.type.template_argument(0).pointer())
762        return valptr.dereference()
763
764class Tr1UnorderedSetPrinter:
765    "Print a tr1::unordered_set"
766
767    def __init__ (self, typename, val):
768        self.typename = typename
769        self.val = val
770
771    def hashtable (self):
772        if self.typename.startswith('std::tr1'):
773            return self.val
774        return self.val['_M_h']
775
776    def to_string (self):
777        return '%s with %d elements' % (self.typename, self.hashtable()['_M_element_count'])
778
779    @staticmethod
780    def format_count (i):
781        return '[%d]' % i
782
783    def children (self):
784        counter = imap (self.format_count, itertools.count())
785        if self.typename.startswith('std::tr1'):
786            return izip (counter, Tr1HashtableIterator (self.hashtable()))
787        return izip (counter, StdHashtableIterator (self.hashtable()))
788
789class Tr1UnorderedMapPrinter:
790    "Print a tr1::unordered_map"
791
792    def __init__ (self, typename, val):
793        self.typename = typename
794        self.val = val
795
796    def hashtable (self):
797        if self.typename.startswith('std::tr1'):
798            return self.val
799        return self.val['_M_h']
800
801    def to_string (self):
802        return '%s with %d elements' % (self.typename, self.hashtable()['_M_element_count'])
803
804    @staticmethod
805    def flatten (list):
806        for elt in list:
807            for i in elt:
808                yield i
809
810    @staticmethod
811    def format_one (elt):
812        return (elt['first'], elt['second'])
813
814    @staticmethod
815    def format_count (i):
816        return '[%d]' % i
817
818    def children (self):
819        counter = imap (self.format_count, itertools.count())
820        # Map over the hash table and flatten the result.
821        if self.typename.startswith('std::tr1'):
822            data = self.flatten (imap (self.format_one, Tr1HashtableIterator (self.hashtable())))
823            # Zip the two iterators together.
824            return izip (counter, data)
825        data = self.flatten (imap (self.format_one, StdHashtableIterator (self.hashtable())))
826        # Zip the two iterators together.
827        return izip (counter, data)
828
829
830    def display_hint (self):
831        return 'map'
832
833class StdForwardListPrinter:
834    "Print a std::forward_list"
835
836    class _iterator(Iterator):
837        def __init__(self, nodetype, head):
838            self.nodetype = nodetype
839            self.base = head['_M_next']
840            self.count = 0
841
842        def __iter__(self):
843            return self
844
845        def __next__(self):
846            if self.base == 0:
847                raise StopIteration
848            elt = self.base.cast(self.nodetype).dereference()
849            self.base = elt['_M_next']
850            count = self.count
851            self.count = self.count + 1
852            valptr = elt['_M_storage'].address
853            valptr = valptr.cast(elt.type.template_argument(0).pointer())
854            return ('[%d]' % count, valptr.dereference())
855
856    def __init__(self, typename, val):
857        self.val = val
858        self.typename = typename
859
860    def children(self):
861        nodetype = find_type(self.val.type, '_Node')
862        nodetype = nodetype.strip_typedefs().pointer()
863        return self._iterator(nodetype, self.val['_M_impl']['_M_head'])
864
865    def to_string(self):
866        if self.val['_M_impl']['_M_head']['_M_next'] == 0:
867            return 'empty %s' % (self.typename)
868        return '%s' % (self.typename)
869
870class SingleObjContainerPrinter(object):
871    "Base class for printers of containers of single objects"
872
873    def __init__ (self, val, viz):
874        self.contained_value = val
875        self.visualizer = viz
876
877    def _recognize(self, type):
878        """Return TYPE as a string after applying type printers"""
879        global _use_type_printing
880        if not _use_type_printing:
881            return str(type)
882        return gdb.types.apply_type_recognizers(gdb.types.get_type_recognizers(),
883                                                type) or str(type)
884
885    class _contained(Iterator):
886        def __init__ (self, val):
887            self.val = val
888
889        def __iter__ (self):
890            return self
891
892        def __next__(self):
893            if self.val is None:
894                raise StopIteration
895            retval = self.val
896            self.val = None
897            return ('[contained value]', retval)
898
899    def children (self):
900        if self.contained_value is None:
901            return self._contained (None)
902        if hasattr (self.visualizer, 'children'):
903            return self.visualizer.children ()
904        return self._contained (self.contained_value)
905
906    def display_hint (self):
907        # if contained value is a map we want to display in the same way
908        if hasattr (self.visualizer, 'children') and hasattr (self.visualizer, 'display_hint'):
909            return self.visualizer.display_hint ()
910        return None
911
912
913class StdExpAnyPrinter(SingleObjContainerPrinter):
914    "Print a std::experimental::any"
915
916    def __init__ (self, typename, val):
917        self.typename = 'std::experimental::any'
918        self.val = val
919        self.contained_type = None
920        contained_value = None
921        visualizer = None
922        mgr = self.val['_M_manager']
923        if mgr != 0:
924            func = gdb.block_for_pc(int(mgr.cast(gdb.lookup_type('intptr_t'))))
925            if not func:
926                raise ValueError("Invalid function pointer in std::experimental::any")
927            rx = r"""({0}::_Manager_\w+<.*>)::_S_manage\({0}::_Op, {0} const\*, {0}::_Arg\*\)""".format(typename)
928            m = re.match(rx, func.function.name)
929            if not m:
930                raise ValueError("Unknown manager function in std::experimental::any")
931
932            # FIXME need to expand 'std::string' so that gdb.lookup_type works
933            mgrname = re.sub("std::string(?!\w)", str(gdb.lookup_type('std::string').strip_typedefs()), m.group(1))
934            mgrtype = gdb.lookup_type(mgrname)
935            self.contained_type = mgrtype.template_argument(0)
936            valptr = None
937            if '::_Manager_internal' in mgrname:
938                valptr = self.val['_M_storage']['_M_buffer'].address
939            elif '::_Manager_external' in mgrname:
940                valptr = self.val['_M_storage']['_M_ptr']
941            elif '::_Manager_alloc' in mgrname:
942                datatype = gdb.lookup_type(mgrname + '::_Data')
943                valptr = self.val['_M_storage']['_M_ptr'].cast(datatype.pointer())
944                valptr = valptr.dereference()['_M_data'].address
945            else:
946                raise ValueError("Unknown manager function in std::experimental::any")
947            contained_value = valptr.cast(self.contained_type.pointer()).dereference()
948            visualizer = gdb.default_visualizer(contained_value)
949        super(StdExpAnyPrinter, self).__init__ (contained_value, visualizer)
950
951    def to_string (self):
952        if self.contained_type is None:
953            return '%s [no contained value]' % self.typename
954        desc = "%s containing " % self.typename
955        if hasattr (self.visualizer, 'children'):
956            return desc + self.visualizer.to_string ()
957        valtype = self._recognize (self.contained_type)
958        return desc + valtype
959
960class StdExpOptionalPrinter(SingleObjContainerPrinter):
961    "Print a std::experimental::optional"
962
963    def __init__ (self, typename, val):
964        valtype = self._recognize (val.type.template_argument(0))
965        self.typename = "std::experimental::optional<%s>" % valtype
966        self.val = val
967        contained_value = val['_M_payload'] if self.val['_M_engaged'] else None
968        visualizer = gdb.default_visualizer (val['_M_payload'])
969        super (StdExpOptionalPrinter, self).__init__ (contained_value, visualizer)
970
971    def to_string (self):
972        if self.contained_value is None:
973            return self.typename + " [no contained value]"
974        if hasattr (self.visualizer, 'children'):
975            return self.typename + " containing " + self.visualizer.to_string ()
976        return self.typename
977
978class StdExpStringViewPrinter:
979    "Print a std::experimental::basic_string_view"
980
981    def __init__ (self, typename, val):
982        self.val = val
983
984    def to_string (self):
985        ptr = self.val['_M_str']
986        len = self.val['_M_len']
987        if hasattr (ptr, "lazy_string"):
988            return ptr.lazy_string (length = len)
989        return ptr.string (length = len)
990
991    def display_hint (self):
992        return 'string'
993
994class StdExpPathPrinter:
995    "Print a std::experimental::filesystem::path"
996
997    def __init__ (self, typename, val):
998        self.val = val
999        start = self.val['_M_cmpts']['_M_impl']['_M_start']
1000        finish = self.val['_M_cmpts']['_M_impl']['_M_finish']
1001        self.num_cmpts = int (finish - start)
1002
1003    def _path_type(self):
1004        t = str(self.val['_M_type'])
1005        if t[-9:] == '_Root_dir':
1006            return "root-directory"
1007        if t[-10:] == '_Root_name':
1008            return "root-name"
1009        return None
1010
1011    def to_string (self):
1012        path = "%s" % self.val ['_M_pathname']
1013        if self.num_cmpts == 0:
1014            t = self._path_type()
1015            if t:
1016                path = '%s [%s]' % (path, t)
1017        return "filesystem::path %s" % path
1018
1019    class _iterator(Iterator):
1020        def __init__(self, cmpts):
1021            self.item = cmpts['_M_impl']['_M_start']
1022            self.finish = cmpts['_M_impl']['_M_finish']
1023            self.count = 0
1024
1025        def __iter__(self):
1026            return self
1027
1028        def __next__(self):
1029            if self.item == self.finish:
1030                raise StopIteration
1031            item = self.item.dereference()
1032            count = self.count
1033            self.count = self.count + 1
1034            self.item = self.item + 1
1035            path = item['_M_pathname']
1036            t = StdExpPathPrinter(item.type.name, item)._path_type()
1037            if not t:
1038                t = count
1039            return ('[%s]' % t, path)
1040
1041    def children(self):
1042        return self._iterator(self.val['_M_cmpts'])
1043
1044
1045# A "regular expression" printer which conforms to the
1046# "SubPrettyPrinter" protocol from gdb.printing.
1047class RxPrinter(object):
1048    def __init__(self, name, function):
1049        super(RxPrinter, self).__init__()
1050        self.name = name
1051        self.function = function
1052        self.enabled = True
1053
1054    def invoke(self, value):
1055        if not self.enabled:
1056            return None
1057
1058        if value.type.code == gdb.TYPE_CODE_REF:
1059            if hasattr(gdb.Value,"referenced_value"):
1060                value = value.referenced_value()
1061
1062        return self.function(self.name, value)
1063
1064# A pretty-printer that conforms to the "PrettyPrinter" protocol from
1065# gdb.printing.  It can also be used directly as an old-style printer.
1066class Printer(object):
1067    def __init__(self, name):
1068        super(Printer, self).__init__()
1069        self.name = name
1070        self.subprinters = []
1071        self.lookup = {}
1072        self.enabled = True
1073        self.compiled_rx = re.compile('^([a-zA-Z0-9_:]+)(<.*>)?$')
1074
1075    def add(self, name, function):
1076        # A small sanity check.
1077        # FIXME
1078        if not self.compiled_rx.match(name):
1079            raise ValueError('libstdc++ programming error: "%s" does not match' % name)
1080        printer = RxPrinter(name, function)
1081        self.subprinters.append(printer)
1082        self.lookup[name] = printer
1083
1084    # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
1085    def add_version(self, base, name, function):
1086        self.add(base + name, function)
1087        self.add(base + '__7::' + name, function)
1088
1089    # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
1090    def add_container(self, base, name, function):
1091        self.add_version(base, name, function)
1092        self.add_version(base + '__cxx1998::', name, function)
1093
1094    @staticmethod
1095    def get_basic_type(type):
1096        # If it points to a reference, get the reference.
1097        if type.code == gdb.TYPE_CODE_REF:
1098            type = type.target ()
1099
1100        # Get the unqualified type, stripped of typedefs.
1101        type = type.unqualified ().strip_typedefs ()
1102
1103        return type.tag
1104
1105    def __call__(self, val):
1106        typename = self.get_basic_type(val.type)
1107        if not typename:
1108            return None
1109
1110        # All the types we match are template types, so we can use a
1111        # dictionary.
1112        match = self.compiled_rx.match(typename)
1113        if not match:
1114            return None
1115
1116        basename = match.group(1)
1117
1118        if val.type.code == gdb.TYPE_CODE_REF:
1119            if hasattr(gdb.Value,"referenced_value"):
1120                val = val.referenced_value()
1121
1122        if basename in self.lookup:
1123            return self.lookup[basename].invoke(val)
1124
1125        # Cannot find a pretty printer.  Return None.
1126        return None
1127
1128libstdcxx_printer = None
1129
1130class TemplateTypePrinter(object):
1131    r"""A type printer for class templates.
1132
1133    Recognizes type names that match a regular expression.
1134    Replaces them with a formatted string which can use replacement field
1135    {N} to refer to the \N subgroup of the regex match.
1136    Type printers are recusively applied to the subgroups.
1137
1138    This allows recognizing e.g. "std::vector<(.*), std::allocator<\\1> >"
1139    and replacing it with "std::vector<{1}>", omitting the template argument
1140    that uses the default type.
1141    """
1142
1143    def __init__(self, name, pattern, subst):
1144        self.name = name
1145        self.pattern = re.compile(pattern)
1146        self.subst = subst
1147        self.enabled = True
1148
1149    class _recognizer(object):
1150        def __init__(self, pattern, subst):
1151            self.pattern = pattern
1152            self.subst = subst
1153            self.type_obj = None
1154
1155        def recognize(self, type_obj):
1156            if type_obj.tag is None:
1157                return None
1158
1159            m = self.pattern.match(type_obj.tag)
1160            if m:
1161                subs = list(m.groups())
1162                for i, sub in enumerate(subs):
1163                    if ('{%d}' % (i+1)) in self.subst:
1164                        # apply recognizers to subgroup
1165                        rep = gdb.types.apply_type_recognizers(
1166                                gdb.types.get_type_recognizers(),
1167                                gdb.lookup_type(sub))
1168                        if rep:
1169                            subs[i] = rep
1170                subs = [None] + subs
1171                return self.subst.format(*subs)
1172            return None
1173
1174    def instantiate(self):
1175        return self._recognizer(self.pattern, self.subst)
1176
1177def add_one_template_type_printer(obj, name, match, subst):
1178    printer = TemplateTypePrinter(name, '^std::' + match + '$', 'std::' + subst)
1179    gdb.types.register_type_printer(obj, printer)
1180
1181class FilteringTypePrinter(object):
1182    def __init__(self, match, name):
1183        self.match = match
1184        self.name = name
1185        self.enabled = True
1186
1187    class _recognizer(object):
1188        def __init__(self, match, name):
1189            self.match = match
1190            self.name = name
1191            self.type_obj = None
1192
1193        def recognize(self, type_obj):
1194            if type_obj.tag is None:
1195                return None
1196
1197            if self.type_obj is None:
1198                if not self.match in type_obj.tag:
1199                    # Filter didn't match.
1200                    return None
1201                try:
1202                    self.type_obj = gdb.lookup_type(self.name).strip_typedefs()
1203                except:
1204                    pass
1205            if self.type_obj == type_obj:
1206                return self.name
1207            return None
1208
1209    def instantiate(self):
1210        return self._recognizer(self.match, self.name)
1211
1212def add_one_type_printer(obj, match, name):
1213    printer = FilteringTypePrinter(match, 'std::' + name)
1214    gdb.types.register_type_printer(obj, printer)
1215
1216def register_type_printers(obj):
1217    global _use_type_printing
1218
1219    if not _use_type_printing:
1220        return
1221
1222    for pfx in ('', 'w'):
1223        add_one_type_printer(obj, 'basic_string', pfx + 'string')
1224        add_one_type_printer(obj, 'basic_ios', pfx + 'ios')
1225        add_one_type_printer(obj, 'basic_streambuf', pfx + 'streambuf')
1226        add_one_type_printer(obj, 'basic_istream', pfx + 'istream')
1227        add_one_type_printer(obj, 'basic_ostream', pfx + 'ostream')
1228        add_one_type_printer(obj, 'basic_iostream', pfx + 'iostream')
1229        add_one_type_printer(obj, 'basic_stringbuf', pfx + 'stringbuf')
1230        add_one_type_printer(obj, 'basic_istringstream',
1231                                 pfx + 'istringstream')
1232        add_one_type_printer(obj, 'basic_ostringstream',
1233                                 pfx + 'ostringstream')
1234        add_one_type_printer(obj, 'basic_stringstream',
1235                                 pfx + 'stringstream')
1236        add_one_type_printer(obj, 'basic_filebuf', pfx + 'filebuf')
1237        add_one_type_printer(obj, 'basic_ifstream', pfx + 'ifstream')
1238        add_one_type_printer(obj, 'basic_ofstream', pfx + 'ofstream')
1239        add_one_type_printer(obj, 'basic_fstream', pfx + 'fstream')
1240        add_one_type_printer(obj, 'basic_regex', pfx + 'regex')
1241        add_one_type_printer(obj, 'sub_match', pfx + 'csub_match')
1242        add_one_type_printer(obj, 'sub_match', pfx + 'ssub_match')
1243        add_one_type_printer(obj, 'match_results', pfx + 'cmatch')
1244        add_one_type_printer(obj, 'match_results', pfx + 'smatch')
1245        add_one_type_printer(obj, 'regex_iterator', pfx + 'cregex_iterator')
1246        add_one_type_printer(obj, 'regex_iterator', pfx + 'sregex_iterator')
1247        add_one_type_printer(obj, 'regex_token_iterator',
1248                                 pfx + 'cregex_token_iterator')
1249        add_one_type_printer(obj, 'regex_token_iterator',
1250                                 pfx + 'sregex_token_iterator')
1251
1252    # Note that we can't have a printer for std::wstreampos, because
1253    # it shares the same underlying type as std::streampos.
1254    add_one_type_printer(obj, 'fpos', 'streampos')
1255    add_one_type_printer(obj, 'basic_string', 'u16string')
1256    add_one_type_printer(obj, 'basic_string', 'u32string')
1257
1258    for dur in ('nanoseconds', 'microseconds', 'milliseconds',
1259                'seconds', 'minutes', 'hours'):
1260        add_one_type_printer(obj, 'duration', dur)
1261
1262    add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand0')
1263    add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand')
1264    add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937')
1265    add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937_64')
1266    add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux24_base')
1267    add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux48_base')
1268    add_one_type_printer(obj, 'discard_block_engine', 'ranlux24')
1269    add_one_type_printer(obj, 'discard_block_engine', 'ranlux48')
1270    add_one_type_printer(obj, 'shuffle_order_engine', 'knuth_b')
1271
1272    # Do not show defaulted template arguments in class templates
1273    add_one_template_type_printer(obj, 'unique_ptr<T>',
1274            'unique_ptr<(.*), std::default_delete<\\1 ?> >',
1275            'unique_ptr<{1}>')
1276
1277    add_one_template_type_printer(obj, 'deque<T>',
1278            'deque<(.*), std::allocator<\\1 ?> >',
1279            'deque<{1}>')
1280    add_one_template_type_printer(obj, 'forward_list<T>',
1281            'forward_list<(.*), std::allocator<\\1 ?> >',
1282            'forward_list<{1}>')
1283    add_one_template_type_printer(obj, 'list<T>',
1284            'list<(.*), std::allocator<\\1 ?> >',
1285            'list<{1}>')
1286    add_one_template_type_printer(obj, 'vector<T>',
1287            'vector<(.*), std::allocator<\\1 ?> >',
1288            'vector<{1}>')
1289    add_one_template_type_printer(obj, 'map<Key, T>',
1290            'map<(.*), (.*), std::less<\\1 ?>, std::allocator<std::pair<\\1 const, \\2 ?> > >',
1291            'map<{1}, {2}>')
1292    add_one_template_type_printer(obj, 'multimap<Key, T>',
1293            'multimap<(.*), (.*), std::less<\\1 ?>, std::allocator<std::pair<\\1 const, \\2 ?> > >',
1294            'multimap<{1}, {2}>')
1295    add_one_template_type_printer(obj, 'set<T>',
1296            'set<(.*), std::less<\\1 ?>, std::allocator<\\1 ?> >',
1297            'set<{1}>')
1298    add_one_template_type_printer(obj, 'multiset<T>',
1299            'multiset<(.*), std::less<\\1 ?>, std::allocator<\\1 ?> >',
1300            'multiset<{1}>')
1301    add_one_template_type_printer(obj, 'unordered_map<Key, T>',
1302            'unordered_map<(.*), (.*), std::hash<\\1 ?>, std::equal_to<\\1 ?>, std::allocator<std::pair<\\1 const, \\2 ?> > >',
1303            'unordered_map<{1}, {2}>')
1304    add_one_template_type_printer(obj, 'unordered_multimap<Key, T>',
1305            'unordered_multimap<(.*), (.*), std::hash<\\1 ?>, std::equal_to<\\1 ?>, std::allocator<std::pair<\\1 const, \\2 ?> > >',
1306            'unordered_multimap<{1}, {2}>')
1307    add_one_template_type_printer(obj, 'unordered_set<T>',
1308            'unordered_set<(.*), std::hash<\\1 ?>, std::equal_to<\\1 ?>, std::allocator<\\1 ?> >',
1309            'unordered_set<{1}>')
1310    add_one_template_type_printer(obj, 'unordered_multiset<T>',
1311            'unordered_multiset<(.*), std::hash<\\1 ?>, std::equal_to<\\1 ?>, std::allocator<\\1 ?> >',
1312            'unordered_multiset<{1}>')
1313
1314    # strip the "fundamentals_v1" inline namespace from these types
1315    add_one_template_type_printer(obj, 'optional<T>',
1316            'experimental::fundamentals_v1::optional<(.*)>',
1317            'experimental::optional<\\1>')
1318    add_one_template_type_printer(obj, 'basic_string_view<C>',
1319            'experimental::fundamentals_v1::basic_string_view<(.*), std::char_traits<\\1> >',
1320            'experimental::basic_string_view<\\1>')
1321
1322def register_libstdcxx_printers (obj):
1323    "Register libstdc++ pretty-printers with objfile Obj."
1324
1325    global _use_gdb_pp
1326    global libstdcxx_printer
1327
1328    if _use_gdb_pp:
1329        gdb.printing.register_pretty_printer(obj, libstdcxx_printer)
1330    else:
1331        if obj is None:
1332            obj = gdb
1333        obj.pretty_printers.append(libstdcxx_printer)
1334
1335    register_type_printers(obj)
1336
1337def build_libstdcxx_dictionary ():
1338    global libstdcxx_printer
1339
1340    libstdcxx_printer = Printer("libstdc++-v6")
1341
1342    # For _GLIBCXX_BEGIN_NAMESPACE_VERSION.
1343    vers = '(__7::)?'
1344    # For _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
1345    container = '(__cxx1998::' + vers + ')?'
1346
1347    # libstdc++ objects requiring pretty-printing.
1348    # In order from:
1349    # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
1350    libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
1351    libstdcxx_printer.add_version('std::', '__cxx11::basic_string', StdStringPrinter)
1352    libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
1353    libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
1354    libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
1355    libstdcxx_printer.add_container('std::__cxx11::', 'list', StdListPrinter)
1356    libstdcxx_printer.add_container('std::', 'map', StdMapPrinter)
1357    libstdcxx_printer.add_container('std::', 'multimap', StdMapPrinter)
1358    libstdcxx_printer.add_container('std::', 'multiset', StdSetPrinter)
1359    libstdcxx_printer.add_version('std::', 'priority_queue',
1360                                  StdStackOrQueuePrinter)
1361    libstdcxx_printer.add_version('std::', 'queue', StdStackOrQueuePrinter)
1362    libstdcxx_printer.add_version('std::', 'tuple', StdTuplePrinter)
1363    libstdcxx_printer.add_container('std::', 'set', StdSetPrinter)
1364    libstdcxx_printer.add_version('std::', 'stack', StdStackOrQueuePrinter)
1365    libstdcxx_printer.add_version('std::', 'unique_ptr', UniquePointerPrinter)
1366    libstdcxx_printer.add_container('std::', 'vector', StdVectorPrinter)
1367    # vector<bool>
1368
1369    # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
1370    libstdcxx_printer.add('std::__debug::bitset', StdBitsetPrinter)
1371    libstdcxx_printer.add('std::__debug::deque', StdDequePrinter)
1372    libstdcxx_printer.add('std::__debug::list', StdListPrinter)
1373    libstdcxx_printer.add('std::__debug::map', StdMapPrinter)
1374    libstdcxx_printer.add('std::__debug::multimap', StdMapPrinter)
1375    libstdcxx_printer.add('std::__debug::multiset', StdSetPrinter)
1376    libstdcxx_printer.add('std::__debug::priority_queue',
1377                          StdStackOrQueuePrinter)
1378    libstdcxx_printer.add('std::__debug::queue', StdStackOrQueuePrinter)
1379    libstdcxx_printer.add('std::__debug::set', StdSetPrinter)
1380    libstdcxx_printer.add('std::__debug::stack', StdStackOrQueuePrinter)
1381    libstdcxx_printer.add('std::__debug::unique_ptr', UniquePointerPrinter)
1382    libstdcxx_printer.add('std::__debug::vector', StdVectorPrinter)
1383
1384    # These are the TR1 and C++0x printers.
1385    # For array - the default GDB pretty-printer seems reasonable.
1386    libstdcxx_printer.add_version('std::', 'shared_ptr', SharedPointerPrinter)
1387    libstdcxx_printer.add_version('std::', 'weak_ptr', SharedPointerPrinter)
1388    libstdcxx_printer.add_container('std::', 'unordered_map',
1389                                    Tr1UnorderedMapPrinter)
1390    libstdcxx_printer.add_container('std::', 'unordered_set',
1391                                    Tr1UnorderedSetPrinter)
1392    libstdcxx_printer.add_container('std::', 'unordered_multimap',
1393                                    Tr1UnorderedMapPrinter)
1394    libstdcxx_printer.add_container('std::', 'unordered_multiset',
1395                                    Tr1UnorderedSetPrinter)
1396    libstdcxx_printer.add_container('std::', 'forward_list',
1397                                    StdForwardListPrinter)
1398
1399    libstdcxx_printer.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter)
1400    libstdcxx_printer.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter)
1401    libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
1402                                  Tr1UnorderedMapPrinter)
1403    libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
1404                                  Tr1UnorderedSetPrinter)
1405    libstdcxx_printer.add_version('std::tr1::', 'unordered_multimap',
1406                                  Tr1UnorderedMapPrinter)
1407    libstdcxx_printer.add_version('std::tr1::', 'unordered_multiset',
1408                                  Tr1UnorderedSetPrinter)
1409
1410    # These are the C++0x printer registrations for -D_GLIBCXX_DEBUG cases.
1411    # The tr1 namespace printers do not seem to have any debug
1412    # equivalents, so do no register them.
1413    libstdcxx_printer.add('std::__debug::unordered_map',
1414                          Tr1UnorderedMapPrinter)
1415    libstdcxx_printer.add('std::__debug::unordered_set',
1416                          Tr1UnorderedSetPrinter)
1417    libstdcxx_printer.add('std::__debug::unordered_multimap',
1418                          Tr1UnorderedMapPrinter)
1419    libstdcxx_printer.add('std::__debug::unordered_multiset',
1420                          Tr1UnorderedSetPrinter)
1421    libstdcxx_printer.add('std::__debug::forward_list',
1422                          StdForwardListPrinter)
1423
1424    # Library Fundamentals TS components
1425    libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
1426                                  'any', StdExpAnyPrinter)
1427    libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
1428                                  'optional', StdExpOptionalPrinter)
1429    libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
1430                                  'basic_string_view', StdExpStringViewPrinter)
1431    # Filesystem TS components
1432    libstdcxx_printer.add_version('std::experimental::filesystem::v1::',
1433                                  'path', StdExpPathPrinter)
1434    libstdcxx_printer.add_version('std::experimental::filesystem::v1::__cxx11::',
1435                                  'path', StdExpPathPrinter)
1436
1437    # Extensions.
1438    libstdcxx_printer.add_version('__gnu_cxx::', 'slist', StdSlistPrinter)
1439
1440    if True:
1441        # These shouldn't be necessary, if GDB "print *i" worked.
1442        # But it often doesn't, so here they are.
1443        libstdcxx_printer.add_container('std::', '_List_iterator',
1444                                        StdListIteratorPrinter)
1445        libstdcxx_printer.add_container('std::', '_List_const_iterator',
1446                                        StdListIteratorPrinter)
1447        libstdcxx_printer.add_version('std::', '_Rb_tree_iterator',
1448                                      StdRbtreeIteratorPrinter)
1449        libstdcxx_printer.add_version('std::', '_Rb_tree_const_iterator',
1450                                      StdRbtreeIteratorPrinter)
1451        libstdcxx_printer.add_container('std::', '_Deque_iterator',
1452                                        StdDequeIteratorPrinter)
1453        libstdcxx_printer.add_container('std::', '_Deque_const_iterator',
1454                                        StdDequeIteratorPrinter)
1455        libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
1456                                      StdVectorIteratorPrinter)
1457        libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
1458                                      StdSlistIteratorPrinter)
1459
1460        # Debug (compiled with -D_GLIBCXX_DEBUG) printer
1461        # registrations.  The Rb_tree debug iterator when unwrapped
1462        # from the encapsulating __gnu_debug::_Safe_iterator does not
1463        # have the __norm namespace. Just use the existing printer
1464        # registration for that.
1465        libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
1466                              StdDebugIteratorPrinter)
1467        libstdcxx_printer.add('std::__norm::_List_iterator',
1468                              StdListIteratorPrinter)
1469        libstdcxx_printer.add('std::__norm::_List_const_iterator',
1470                              StdListIteratorPrinter)
1471        libstdcxx_printer.add('std::__norm::_Deque_const_iterator',
1472                              StdDequeIteratorPrinter)
1473        libstdcxx_printer.add('std::__norm::_Deque_iterator',
1474                              StdDequeIteratorPrinter)
1475
1476build_libstdcxx_dictionary ()
1477