1 # Pretty-printer utilities.
2 # Copyright (C) 2010-2023 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."""
25 class PrettyPrinter(object):
26 """A basic pretty-printer.
29 name: A unique string among all printers for the context in which
30 it is defined (objfile, progspace, or global(gdb)), and should
31 meaningfully describe what can be pretty-printed.
32 E.g., "StringPiece" or "protobufs".
33 subprinters: An iterable object with each element having a `name'
34 attribute, and, potentially, "enabled" attribute.
35 Or this is None if there are no subprinters.
36 enabled: A boolean indicating if the printer is enabled.
38 Subprinters are for situations where "one" pretty-printer is actually a
39 collection of several printers. E.g., The libstdc++ pretty-printer has
40 a pretty-printer for each of several different types, based on regexps.
43 # While one might want to push subprinters into the subclass, it's
44 # present here to formalize such support to simplify
45 # commands/pretty_printers.py.
47 def __init__(self
, name
, subprinters
=None):
49 self
.subprinters
= subprinters
52 def __call__(self
, val
):
53 # The subclass must define this.
54 raise NotImplementedError("PrettyPrinter __call__")
57 class SubPrettyPrinter(object):
58 """Baseclass for sub-pretty-printers.
60 Sub-pretty-printers needn't use this, but it formalizes what's needed.
63 name: The name of the subprinter.
64 enabled: A boolean indicating if the subprinter is enabled.
67 def __init__(self
, name
):
72 def register_pretty_printer(obj
, printer
, replace
=False):
73 """Register pretty-printer PRINTER with OBJ.
75 The printer is added to the front of the search list, thus one can override
76 an existing printer if one needs to. Use a different name when overriding
77 an existing printer, otherwise an exception will be raised; multiple
78 printers with the same name are disallowed.
81 obj: Either an objfile, progspace, or None (in which case the printer
82 is registered globally).
83 printer: Either a function of one argument (old way) or any object
84 which has attributes: name, enabled, __call__.
85 replace: If True replace any existing copy of the printer.
86 Otherwise if the printer already exists raise an exception.
92 TypeError: A problem with the type of the printer.
93 ValueError: The printer's name contains a semicolon ";".
94 RuntimeError: A printer with the same name is already registered.
96 If the caller wants the printer to be listable and disableable, it must
97 follow the PrettyPrinter API. This applies to the old way (functions) too.
98 If printer is an object, __call__ is a method of two arguments:
99 self, and the value to be pretty-printed. See PrettyPrinter.
102 # Watch for both __name__ and name.
103 # Functions get the former for free, but we don't want to use an
104 # attribute named __foo__ for pretty-printers-as-objects.
105 # If printer has both, we use `name'.
106 if not hasattr(printer
, "__name__") and not hasattr(printer
, "name"):
107 raise TypeError("printer missing attribute: name")
108 if hasattr(printer
, "name") and not hasattr(printer
, "enabled"):
109 raise TypeError("printer missing attribute: enabled")
110 if not hasattr(printer
, "__call__"):
111 raise TypeError("printer missing attribute: __call__")
113 if hasattr(printer
, "name"):
116 name
= printer
.__name
__
117 if obj
is None or obj
is gdb
:
118 if gdb
.parameter("verbose"):
119 gdb
.write("Registering global %s pretty-printer ...\n" % name
)
122 if gdb
.parameter("verbose"):
124 "Registering %s pretty-printer for %s ...\n" % (name
, obj
.filename
)
127 # Printers implemented as functions are old-style. In order to not risk
128 # breaking anything we do not check __name__ here.
129 if hasattr(printer
, "name"):
130 if not isinstance(printer
.name
, str):
131 raise TypeError("printer name is not a string")
132 # If printer provides a name, make sure it doesn't contain ";".
133 # Semicolon is used by the info/enable/disable pretty-printer commands
134 # to delimit subprinters.
135 if printer
.name
.find(";") >= 0:
136 raise ValueError("semicolon ';' in printer name")
137 # Also make sure the name is unique.
138 # Alas, we can't do the same for functions and __name__, they could
139 # all have a canonical name like "lookup_function".
140 # PERF: gdb records printers in a list, making this inefficient.
142 for p
in obj
.pretty_printers
:
143 if hasattr(p
, "name") and p
.name
== printer
.name
:
145 del obj
.pretty_printers
[i
]
149 "pretty-printer already registered: %s" % printer
.name
153 obj
.pretty_printers
.insert(0, printer
)
156 class RegexpCollectionPrettyPrinter(PrettyPrinter
):
157 """Class for implementing a collection of regular-expression based pretty-printers.
161 pretty_printer = RegexpCollectionPrettyPrinter("my_library")
162 pretty_printer.add_printer("myclass1", "^myclass1$", MyClass1Printer)
164 pretty_printer.add_printer("myclassN", "^myclassN$", MyClassNPrinter)
165 register_pretty_printer(obj, pretty_printer)
168 class RegexpSubprinter(SubPrettyPrinter
):
169 def __init__(self
, name
, regexp
, gen_printer
):
170 super(RegexpCollectionPrettyPrinter
.RegexpSubprinter
, self
).__init
__(name
)
172 self
.gen_printer
= gen_printer
173 self
.compiled_re
= re
.compile(regexp
)
175 def __init__(self
, name
):
176 super(RegexpCollectionPrettyPrinter
, self
).__init
__(name
, [])
178 def add_printer(self
, name
, regexp
, gen_printer
):
179 """Add a printer to the list.
181 The printer is added to the end of the list.
184 name: The name of the subprinter.
185 regexp: The regular expression, as a string.
186 gen_printer: A function/method that given a value returns an
187 object to pretty-print it.
193 # NOTE: A previous version made the name of each printer the regexp.
194 # That makes it awkward to pass to the enable/disable commands (it's
195 # cumbersome to make a regexp of a regexp). So now the name is a
196 # separate parameter.
198 self
.subprinters
.append(self
.RegexpSubprinter(name
, regexp
, gen_printer
))
200 def __call__(self
, val
):
201 """Lookup the pretty-printer for the provided value."""
204 typename
= gdb
.types
.get_basic_type(val
.type).tag
206 typename
= val
.type.name
210 # Iterate over table of type regexps to determine
211 # if a printer is registered for that type.
212 # Return an instantiation of the printer if found.
213 for printer
in self
.subprinters
:
214 if printer
.enabled
and printer
.compiled_re
.search(typename
):
215 return printer
.gen_printer(val
)
217 # Cannot find a pretty printer. Return None.
221 # A helper class for printing enum types. This class is instantiated
222 # with a list of enumerators to print a particular Value.
224 def __init__(self
, enumerators
, val
):
225 self
.enumerators
= enumerators
232 for e_name
, e_value
in self
.enumerators
:
234 flag_list
.append(e_name
)
237 if not any_found
or v
!= 0:
239 flag_list
.append("<unknown: 0x%x>" % v
)
240 return "0x%x [%s]" % (int(self
.val
), " | ".join(flag_list
))
243 class FlagEnumerationPrinter(PrettyPrinter
):
244 """A pretty-printer which can be used to print a flag-style enumeration.
245 A flag-style enumeration is one where the enumerators are or'd
246 together to create values. The new printer will print these
247 symbolically using '|' notation. The printer must be registered
248 manually. This printer is most useful when an enum is flag-like,
249 but has some overlap. GDB's built-in printing will not handle
250 this case, but this printer will attempt to."""
252 def __init__(self
, enum_type
):
253 super(FlagEnumerationPrinter
, self
).__init
__(enum_type
)
254 self
.initialized
= False
256 def __call__(self
, val
):
257 if not self
.initialized
:
258 self
.initialized
= True
259 flags
= gdb
.lookup_type(self
.name
)
260 self
.enumerators
= []
261 for field
in flags
.fields():
262 self
.enumerators
.append((field
.name
, field
.enumval
))
263 # Sorting the enumerators by value usually does the right
265 self
.enumerators
.sort(key
=lambda x
: x
[1])
268 return _EnumInstance(self
.enumerators
, val
)
273 class NoOpScalarPrinter
:
274 """A no-op pretty printer that wraps a scalar value."""
276 def __init__(self
, value
):
280 return self
.value
.format_string(raw
=True)
283 class NoOpPointerReferencePrinter
:
284 """A no-op pretty printer that wraps a pointer or reference."""
286 def __init__(self
, value
):
288 self
.num_children
= 1
291 return self
.value
.format_string(deref_refs
=False)
294 yield "value", self
.value
.referenced_value()
297 class NoOpArrayPrinter
:
298 """A no-op pretty printer that wraps an array value."""
300 def __init__(self
, ty
, value
):
302 (low
, high
) = ty
.range()
303 # In Ada, an array can have an index type that is a
304 # non-contiguous enum. In this case the indexing must be done
305 # by using the indices into the enum type, not the underlying
307 range_type
= ty
.fields()[0].type
308 if range_type
.target().code
== gdb
.TYPE_CODE_ENUM
:
309 e_values
= range_type
.target().fields()
310 # Drop any values before LOW.
311 e_values
= itertools
.dropwhile(lambda x
: x
.enumval
< low
, e_values
)
312 # Drop any values after HIGH.
313 e_values
= itertools
.takewhile(lambda x
: x
.enumval
<= high
, e_values
)
315 high
= len(list(e_values
)) - 1
316 # This is a convenience to the DAP code and perhaps other
318 self
.num_children
= high
- low
+ 1
325 def display_hint(self
):
329 for i
in range(self
.low
, self
.high
+ 1):
330 yield (i
, self
.value
[i
])
333 class NoOpStructPrinter
:
334 """A no-op pretty printer that wraps a struct or union value."""
336 def __init__(self
, ty
, value
):
344 for field
in self
.ty
.fields():
345 if field
.name
is not None:
346 yield (field
.name
, self
.value
[field
])
349 def make_visualizer(value
):
350 """Given a gdb.Value, wrap it in a pretty-printer.
352 If a pretty-printer is found by the usual means, it is returned.
353 Otherwise, VALUE will be wrapped in a no-op visualizer."""
355 result
= gdb
.default_visualizer(value
)
356 if result
is not None:
357 # Found a pretty-printer.
360 ty
= value
.type.strip_typedefs()
361 if ty
.is_string_like
:
362 result
= gdb
.printing
.NoOpScalarPrinter(value
)
363 elif ty
.code
== gdb
.TYPE_CODE_ARRAY
:
364 result
= gdb
.printing
.NoOpArrayPrinter(ty
, value
)
365 elif ty
.is_array_like
:
366 value
= value
.to_array()
367 ty
= value
.type.strip_typedefs()
368 result
= gdb
.printing
.NoOpArrayPrinter(ty
, value
)
369 elif ty
.code
in (gdb
.TYPE_CODE_STRUCT
, gdb
.TYPE_CODE_UNION
):
370 result
= gdb
.printing
.NoOpStructPrinter(ty
, value
)
371 elif ty
.code
in (gdb
.TYPE_CODE_PTR
, gdb
.TYPE_CODE_REF
, gdb
.TYPE_CODE_RVALUE_REF
):
372 result
= NoOpPointerReferencePrinter(value
)
374 result
= gdb
.printing
.NoOpScalarPrinter(value
)
378 # Builtin pretty-printers.
379 # The set is defined as empty, and files in printing/*.py add their printers
380 # to this with add_builtin_pretty_printer.
382 _builtin_pretty_printers
= RegexpCollectionPrettyPrinter("builtin")
384 register_pretty_printer(None, _builtin_pretty_printers
)
386 # Add a builtin pretty-printer.
389 def add_builtin_pretty_printer(name
, regexp
, printer
):
390 _builtin_pretty_printers
.add_printer(name
, regexp
, printer
)