summaryrefslogtreecommitdiffstats
path: root/validate.py
blob: ebe597759c1003032106fcf265e999c1e293d9ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""
Hooks for validating CPython extension source code
"""
class CExtensionError(Exception):
    # Base class for errors discovered by static analysis in C extension code
    def __init__(self, location):
        self.location = location

    def __str__(self):
        return '%s:%s:%s:%s' % (self.location.file, 
                                self.location.line,
                                self.location.current_element,
                                self._get_desc())

    def _get_desc(self):
        raise NotImplementedError

class UnknownFormatChar(CExtensionError):
    def __init__(self, location, ch):
        CExtensionError.__init__(self, location)
        self.ch = ch

    def _get_desc(self):
        return "unknown format char: '%s'" % self.ch

class UnhandledCode(UnknownFormatChar):
    def _get_desc(self):
        return "unhandled format code: '%s' (FIXME)" % self.ch


def get_types(location, strfmt):
    """
    Generate a list of C type names from a PyArg_ParseTuple format string
    Compare to Python/getargs.c:vgetargs1
    FIXME: only implements a very small subset of the various cases; no tuples, etc
    """
    result = []
    i = 0
    while i < len(strfmt):
        c = strfmt[i]
        i += 1
        if i < len(strfmt):
            next = strfmt[i]
        else:
            next = None

        # FIXME: '(', ')'

        if c in [':', ';']:
            break

        if c =='|':
            continue

        # From convertsimple:
        simple = {'b':'char',
                  'B':'char',
                  'h':'short',
                  'H':'short',
                  'i':'int',
                  'I':'int',
                  'n':'Py_ssize_t',
                  'l':'long',
                  'k':'unsigned long',
                  # L, K: FIXME
                  'f':'float',
                  'd':'double',
                  # D: FIXME,
                  'c':'char',
                  }
        if c in simple:
            result.append(simple[c] + ' *')

        elif c in ['s', 'z']: # string, possibly NULL/None
            if next == '#':
                result += ['const char * *', 'int *']
                i += 1
            elif next == '*':
                result.append('Py_buffer *')
                i += 1
            else:
                result.append('const char * *')
            # FIXME: seeing lots of (const char**) versus (char**) mismatches here
            # do we care?

        elif c == 'e':
            if next in ['s', 't']:
                result += ['const char *', 'char * *']
                i += 1
                if i < len(strfmt):
                    if strfmt[i] == '#':
                        result.append('int *')
        elif c == 'S':
            result.append('PyObject * *')
        elif c == 'U':
            result.append('PyObject * *')
        elif c == 'O': # object
            if next == '!':
                result += ['PyTypeObject *', 'PyObject * *']
                i += 1
            elif next == '?':
                raise UnhandledCode(location, c + next) # FIXME
            elif next == '&':
                # FIXME: can't really handle this case as is, fixing for fcntmodule.c
                result += ['int ( PyObject * object , int * target )',  # converter
                           'int *'] # FIXME, anything
                i += 1
            else:
                result.append('PyObject * *')
        elif c == 'w':
            raise UnhandledCode(location, c) # FIXME
        elif c == 't':
            if next == '#':
                result += ['char * *', 'int *']
                i += 1
        else:
            raise UnknownFormatChar(location, c)
    return result
                              

class WrongNumberOfVars(CExtensionError):
    def __init__(self, location, exp_types, actual_types):
        CExtensionError.__init__(self, location)
        self.exp_types = exp_types
        self.actual_types = actual_types

class NotEnoughVars(WrongNumberOfVars):
    def _get_desc(self):
        return 'Not enough arguments: expected %i (%s), but got %i (%s)' % (
            len(self.exp_types),
            self.exp_types,
            len(self.actual_types),
            self.actual_types)

class TooManyVars(WrongNumberOfVars):
    def _get_desc(self):
        return 'Too many arguments: expected %i (%s), but got %i (%s)' % (
            len(self.exp_types),
            self.exp_types,
            len(self.actual_types),
            self.actual_types)

class MismatchingType(CExtensionError):
    def __init__(self, location, arg_num, exp_type, actual_type):
        super(self.__class__, self).__init__(location)
        self.arg_num = arg_num
        self.exp_type = exp_type
        self.actual_type = actual_type

    def _get_desc(self):
        return 'Mismatching type of argument %i: expected "%s" but got "%s"' % (
            self.arg_num,
            self.exp_type,
            self.actual_type)


def type_equality(t1, t2):
    if t1 == t2:
        return True

    # do we really care about char/const char mismatches?:
    if t1.startswith('const char *'):
        if t1 == 'const '+t2:
            return True
    if t2.startswith('const char *'):
        if 'const '+t1 == t2:
            return True

    return False


def validate_types(location, format_string, actual_types):
    if False:
        print 'validate_types(%s, %s, %s)' % (
            repr(location), repr(format_string), repr(actual_types))
    try:
        exp_types = get_types(location, format_string[1:-1]) # strip leading and trailing " chars
        if len(actual_types) < len(exp_types):
            raise NotEnoughVars(location, exp_types, actual_types)
        if len(actual_types) > len(exp_types):
            raise TooManyVars(location, exp_types, actual_types)
        for i, (exp, actual) in enumerate(zip(exp_types, actual_types)):
            if not type_equality(exp, actual):
                raise MismatchingType(location, i+1, exp, actual)
    except CExtensionError, err:
        print err
        if False:
            print 'validate_types(%s, %s, %s)' % (
                repr(location), repr(format_string), repr(actual_types))
        return 1
    return 0

import unittest
class TestArgParsing(unittest.TestCase):
    def assert_args(self, arg_str, exp_result):
        result = get_types(None, arg_str)
        self.assertEquals(result, exp_result)

    def test_simple_cases(self):
        self.assert_args('c',
                         ['char *'])

    def test_socketmodule_socket_htons(self):
        self.assert_args('i:htons',
                         ['int *'])

    def test_fcntlmodule_fcntl_flock(self):
        # FIXME: somewhat broken, we can't know what the converter callback is
        self.assert_args("O&i:flock", 
                         ['int ( PyObject * object , int * target )', 
                          'int *', 
                          'int *'])


if __name__ == '__main__':
    unittest.main()