1# Pretty-printer utilities.
2# Copyright (C) 2010-2012 Free Software Foundation, Inc.
3
4# This program is free software; you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation; either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17"""Utilities for working with pretty-printers."""
18
19import gdb
20import gdb.types
21import re
22
23
24class PrettyPrinter(object):
25    """A basic pretty-printer.
26
27    Attributes:
28        name: A unique string among all printers for the context in which
29            it is defined (objfile, progspace, or global(gdb)), and should
30            meaningfully describe what can be pretty-printed.
31            E.g., "StringPiece" or "protobufs".
32        subprinters: An iterable object with each element having a `name'
33            attribute, and, potentially, "enabled" attribute.
34            Or this is None if there are no subprinters.
35        enabled: A boolean indicating if the printer is enabled.
36
37    Subprinters are for situations where "one" pretty-printer is actually a
38    collection of several printers.  E.g., The libstdc++ pretty-printer has
39    a pretty-printer for each of several different types, based on regexps.
40    """
41
42    # While one might want to push subprinters into the subclass, it's
43    # present here to formalize such support to simplify
44    # commands/pretty_printers.py.
45
46    def __init__(self, name, subprinters=None):
47        self.name = name
48        self.subprinters = subprinters
49        self.enabled = True
50
51    def __call__(self, val):
52        # The subclass must define this.
53        raise NotImplementedError("PrettyPrinter __call__")
54
55
56class SubPrettyPrinter(object):
57    """Baseclass for sub-pretty-printers.
58
59    Sub-pretty-printers needn't use this, but it formalizes what's needed.
60
61    Attributes:
62        name: The name of the subprinter.
63        enabled: A boolean indicating if the subprinter is enabled.
64    """
65
66    def __init__(self, name):
67        self.name = name
68        self.enabled = True
69
70
71def register_pretty_printer(obj, printer, replace=False):
72    """Register pretty-printer PRINTER with OBJ.
73
74    The printer is added to the front of the search list, thus one can override
75    an existing printer if one needs to.  Use a different name when overriding
76    an existing printer, otherwise an exception will be raised; multiple
77    printers with the same name are disallowed.
78
79    Arguments:
80        obj: Either an objfile, progspace, or None (in which case the printer
81            is registered globally).
82        printer: Either a function of one argument (old way) or any object
83            which has attributes: name, enabled, __call__.
84        replace: If True replace any existing copy of the printer.
85            Otherwise if the printer already exists raise an exception.
86
87    Returns:
88        Nothing.
89
90    Raises:
91        TypeError: A problem with the type of the printer.
92        ValueError: The printer's name contains a semicolon ";".
93        RuntimeError: A printer with the same name is already registered.
94
95    If the caller wants the printer to be listable and disableable, it must
96    follow the PrettyPrinter API.  This applies to the old way (functions) too.
97    If printer is an object, __call__ is a method of two arguments:
98    self, and the value to be pretty-printed.  See PrettyPrinter.
99    """
100
101    # Watch for both __name__ and name.
102    # Functions get the former for free, but we don't want to use an
103    # attribute named __foo__ for pretty-printers-as-objects.
104    # If printer has both, we use `name'.
105    if not hasattr(printer, "__name__") and not hasattr(printer, "name"):
106        raise TypeError("printer missing attribute: name")
107    if hasattr(printer, "name") and not hasattr(printer, "enabled"):
108        raise TypeError("printer missing attribute: enabled")
109    if not hasattr(printer, "__call__"):
110        raise TypeError("printer missing attribute: __call__")
111
112    if obj is None:
113        if gdb.parameter("verbose"):
114            gdb.write("Registering global %s pretty-printer ...\n" % name)
115        obj = gdb
116    else:
117        if gdb.parameter("verbose"):
118            gdb.write("Registering %s pretty-printer for %s ...\n" %
119                      (printer.name, obj.filename))
120
121    if hasattr(printer, "name"):
122        if not isinstance(printer.name, basestring):
123            raise TypeError("printer name is not a string")
124        # If printer provides a name, make sure it doesn't contain ";".
125        # Semicolon is used by the info/enable/disable pretty-printer commands
126        # to delimit subprinters.
127        if printer.name.find(";") >= 0:
128            raise ValueError("semicolon ';' in printer name")
129        # Also make sure the name is unique.
130        # Alas, we can't do the same for functions and __name__, they could
131        # all have a canonical name like "lookup_function".
132        # PERF: gdb records printers in a list, making this inefficient.
133        i = 0
134        for p in obj.pretty_printers:
135            if hasattr(p, "name") and p.name == printer.name:
136                if replace:
137                    del obj.pretty_printers[i]
138                    break
139                else:
140                  raise RuntimeError("pretty-printer already registered: %s" %
141                                     printer.name)
142            i = i + 1
143
144    obj.pretty_printers.insert(0, printer)
145
146
147class RegexpCollectionPrettyPrinter(PrettyPrinter):
148    """Class for implementing a collection of regular-expression based pretty-printers.
149
150    Intended usage:
151
152    pretty_printer = RegexpCollectionPrettyPrinter("my_library")
153    pretty_printer.add_printer("myclass1", "^myclass1$", MyClass1Printer)
154    ...
155    pretty_printer.add_printer("myclassN", "^myclassN$", MyClassNPrinter)
156    register_pretty_printer(obj, pretty_printer)
157    """
158
159    class RegexpSubprinter(SubPrettyPrinter):
160        def __init__(self, name, regexp, gen_printer):
161            super(RegexpCollectionPrettyPrinter.RegexpSubprinter, self).__init__(name)
162            self.regexp = regexp
163            self.gen_printer = gen_printer
164            self.compiled_re = re.compile(regexp)
165
166    def __init__(self, name):
167        super(RegexpCollectionPrettyPrinter, self).__init__(name, [])
168
169    def add_printer(self, name, regexp, gen_printer):
170        """Add a printer to the list.
171
172        The printer is added to the end of the list.
173
174        Arguments:
175            name: The name of the subprinter.
176            regexp: The regular expression, as a string.
177            gen_printer: A function/method that given a value returns an
178                object to pretty-print it.
179
180        Returns:
181            Nothing.
182        """
183
184        # NOTE: A previous version made the name of each printer the regexp.
185        # That makes it awkward to pass to the enable/disable commands (it's
186        # cumbersome to make a regexp of a regexp).  So now the name is a
187        # separate parameter.
188
189        self.subprinters.append(self.RegexpSubprinter(name, regexp,
190                                                      gen_printer))
191
192    def __call__(self, val):
193        """Lookup the pretty-printer for the provided value."""
194
195        # Get the type name.
196        typename = gdb.types.get_basic_type(val.type).tag
197        if not typename:
198            return None
199
200        # Iterate over table of type regexps to determine
201        # if a printer is registered for that type.
202        # Return an instantiation of the printer if found.
203        for printer in self.subprinters:
204            if printer.enabled and printer.compiled_re.search(typename):
205                return printer.gen_printer(val)
206
207        # Cannot find a pretty printer.  Return None.
208        return None
209