1 # Pretty-printer utilities.
2 # Copyright (C) 2010-2012 Free Software Foundation, Inc.
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.
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.
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/>.
17 """Utilities for working with pretty-printers."""
24 class PrettyPrinter(object):
25 """A basic pretty-printer.
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.
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.
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.
46 def __init__(self, name, subprinters=None):
48 self.subprinters = subprinters
51 def __call__(self, val):
52 # The subclass must define this.
53 raise NotImplementedError("PrettyPrinter __call__")
56 class SubPrettyPrinter(object):
57 """Baseclass for sub-pretty-printers.
59 Sub-pretty-printers needn't use this, but it formalizes what's needed.
62 name: The name of the subprinter.
63 enabled: A boolean indicating if the subprinter is enabled.
66 def __init__(self, name):
71 def register_pretty_printer(obj, printer, replace=False):
72 """Register pretty-printer PRINTER with OBJ.
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.
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.
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.
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.
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__")
113 if gdb.parameter("verbose"):
114 gdb.write("Registering global %s pretty-printer ...\n" % name)
117 if gdb.parameter("verbose"):
118 gdb.write("Registering %s pretty-printer for %s ...\n" %
119 (printer.name, obj.filename))
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.
134 for p in obj.pretty_printers:
135 if hasattr(p, "name") and p.name == printer.name:
137 del obj.pretty_printers[i]
140 raise RuntimeError("pretty-printer already registered: %s" %
144 obj.pretty_printers.insert(0, printer)
147 class RegexpCollectionPrettyPrinter(PrettyPrinter):
148 """Class for implementing a collection of regular-expression based pretty-printers.
152 pretty_printer = RegexpCollectionPrettyPrinter("my_library")
153 pretty_printer.add_printer("myclass1", "^myclass1$", MyClass1Printer)
155 pretty_printer.add_printer("myclassN", "^myclassN$", MyClassNPrinter)
156 register_pretty_printer(obj, pretty_printer)
159 class RegexpSubprinter(SubPrettyPrinter):
160 def __init__(self, name, regexp, gen_printer):
161 super(RegexpCollectionPrettyPrinter.RegexpSubprinter, self).__init__(name)
163 self.gen_printer = gen_printer
164 self.compiled_re = re.compile(regexp)
166 def __init__(self, name):
167 super(RegexpCollectionPrettyPrinter, self).__init__(name, [])
169 def add_printer(self, name, regexp, gen_printer):
170 """Add a printer to the list.
172 The printer is added to the end of the list.
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.
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.
189 self.subprinters.append(self.RegexpSubprinter(name, regexp,
192 def __call__(self, val):
193 """Lookup the pretty-printer for the provided value."""
196 typename = gdb.types.get_basic_type(val.type).tag
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)
207 # Cannot find a pretty printer. Return None.