1# Copyright (C) 2008-2020 Free Software Foundation, Inc.
2
3# This program is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation; either version 3 of the License, or
6# (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16# This file is part of the GDB testsuite.  It tests GDB's handling of
17# bad python pretty printers.
18
19# Test a printer with a bad children iterator.
20
21import re
22import gdb.printing
23
24
25class BadChildrenContainerPrinter1(object):
26    """Children iterator doesn't return a tuple of two elements."""
27
28    def __init__(self, val):
29        self.val = val
30
31    def to_string(self):
32        return 'container %s with %d elements' % (self.val['name'], self.val['len'])
33
34    @staticmethod
35    def _bad_iterator(pointer, len):
36        start = pointer
37        end = pointer + len
38        while pointer != end:
39            yield 'intentional violation of children iterator protocol'
40            pointer += 1
41
42    def children(self):
43        return self._bad_iterator(self.val['elements'], self.val['len'])
44
45
46class BadChildrenContainerPrinter2(object):
47    """Children iterator returns a tuple of two elements with bad values."""
48
49    def __init__(self, val):
50        self.val = val
51
52    def to_string(self):
53        return 'container %s with %d elements' % (self.val['name'], self.val['len'])
54
55    @staticmethod
56    def _bad_iterator(pointer, len):
57        start = pointer
58        end = pointer + len
59        while pointer != end:
60            # The first argument is supposed to be a string.
61            yield (42, 'intentional violation of children iterator protocol')
62            pointer += 1
63
64    def children(self):
65        return self._bad_iterator(self.val['elements'], self.val['len'])
66
67
68def build_pretty_printer():
69    pp = gdb.printing.RegexpCollectionPrettyPrinter("bad-printers")
70
71    pp.add_printer('container1', '^container$',
72                   BadChildrenContainerPrinter1)
73    pp.add_printer('container2', '^container$',
74                   BadChildrenContainerPrinter2)
75
76    return pp
77
78
79my_pretty_printer = build_pretty_printer()
80gdb.printing.register_pretty_printer(gdb, my_pretty_printer)
81