File: utils.py

package info (click to toggle)
spring 103.0%2Bdfsg2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 43,720 kB
  • ctags: 63,685
  • sloc: cpp: 368,283; ansic: 33,988; python: 12,417; java: 12,203; awk: 5,879; sh: 1,846; xml: 655; perl: 405; php: 211; objc: 194; makefile: 77; sed: 2
file content (243 lines) | stat: -rw-r--r-- 7,688 bytes parent folder | download | duplicates (7)
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
try:
    any = any
except NameError:
    def any(iterable):
        for element in iterable:
            if element:
                return True
        return False


import sys
from typehandlers.codesink import CodeSink
from typehandlers.base import TypeLookupError, TypeConfigurationError, CodeGenerationError, NotSupportedError, \
    Parameter, ReturnValue
import version
import settings
import warnings


def write_preamble(code_sink, min_python_version=None):
    """
    Write a preamble, containing includes, #define's and typedef's
    necessary to correctly compile the code with the given minimum python
    version.
    """
    if min_python_version is None:
        min_python_version = settings.min_python_version
    assert isinstance(code_sink, CodeSink)
    assert isinstance(min_python_version, tuple)

    if __debug__:
        ## Gracefully allow code migration
        if hasattr(code_sink, "have_written_preamble"):
            warnings.warn("Duplicate call to write_preamble detected.  "
                          "Note that there has been an API change in PyBindGen "
                          "and directly calling write_preamble should no longer be done "
                          "as it is done by PyBindGen itself.",
                          DeprecationWarning, stacklevel=2)
            return
        else:
            setattr(code_sink, "have_written_preamble", None)

    code_sink.writeln('''/* This file was generated by PyBindGen %s */
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stddef.h>
''' % '.'.join([str(x) for x in version.__version__]))

    if min_python_version < (2, 4):
        code_sink.writeln(r'''
#if PY_VERSION_HEX < 0x020400F0

#define PyEval_ThreadsInitialized() 1

#define Py_CLEAR(op)				\
        do {                            	\
                if (op) {			\
                        PyObject *tmp = (PyObject *)(op);	\
                        (op) = NULL;		\
                        Py_DECREF(tmp);		\
                }				\
        } while (0)


#define Py_VISIT(op)							\
        do { 								\
                if (op) {						\
                        int vret = visit((PyObject *)(op), arg);	\
                        if (vret)					\
                                return vret;				\
                }							\
        } while (0)

#endif

''')

    if min_python_version < (2, 5):
        code_sink.writeln(r'''
#if PY_VERSION_HEX < 0x020500F0

typedef int Py_ssize_t;
# define PY_SSIZE_T_MAX INT_MAX
# define PY_SSIZE_T_MIN INT_MIN
typedef inquiry lenfunc;
typedef intargfunc ssizeargfunc;
typedef intobjargproc ssizeobjargproc;

#endif
''')

    code_sink.writeln(r'''
#if     __GNUC__ > 2
# define PYBINDGEN_UNUSED(param) param __attribute__((__unused__))
#elif     __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 4)
# define PYBINDGEN_UNUSED(param) __attribute__((__unused__)) param
#else
# define PYBINDGEN_UNUSED(param) param
#endif  /* !__GNUC__ */

typedef enum _PyBindGenWrapperFlags {
   PYBINDGEN_WRAPPER_FLAG_NONE = 0,
   PYBINDGEN_WRAPPER_FLAG_OBJECT_NOT_OWNED = (1<<0),
} PyBindGenWrapperFlags;

''')
    

def mangle_name(name):
    """make a name Like<This,and,That> look Like__lt__This_and_That__gt__"""
    s = name.replace('<', '__lt__').replace('>', '__gt__').replace(',', '_')
    s = s.replace(' ', '_').replace('&', '__amp__').replace('*', '__star__')
    s = s.replace(':', '_')
    s = s.replace('(', '_lp_').replace(')', '_rp_')
    return s


def get_mangled_name(base_name, template_args):
    """for internal pybindgen use"""
    assert isinstance(base_name, basestring)
    assert isinstance(template_args, (tuple, list))

    if template_args:
        return '%s__lt__%s__gt__' % (mangle_name(base_name), '_'.join(
                [mangle_name(arg) for arg in template_args]))
    else:
        return mangle_name(base_name)


class SkipWrapper(Exception):
    """Exception that is raised to signal a wrapper failed to generate but
    must simply be skipped.
    for internal pybindgen use"""

def call_with_error_handling(callback, args, kwargs, wrapper,
                             exceptions_to_handle=(TypeConfigurationError,
                                                   CodeGenerationError,
                                                   NotSupportedError)):
    """for internal pybindgen use"""
    if settings.error_handler is None:
        return callback(*args, **kwargs)
    else:
        try:
            return callback(*args, **kwargs)
        except Exception, ex:
            if isinstance(ex, exceptions_to_handle):
                dummy1, dummy2, traceback = sys.exc_info()
                if settings.error_handler.handle_error(wrapper, ex, traceback):
                    raise SkipWrapper
                else:
                    raise
            else:
                raise


def ascii(value):
    """
    ascii(str_or_unicode_or_None) -> str_or_None

    Make sure the value is either str or unicode object, and if it is
    unicode convert it to ascii.  Also, None is an accepted value, and
    returns itself.
    """
    if value is None:
        return value
    elif isinstance(value, str):
        return value
    elif isinstance(value, unicode):
        return value.encode('ascii')
    else:
        raise TypeError("value must be str or ascii string contained in a unicode object")


def param(*args, **kwargs):
    """
    Simplified syntax for representing a parameter with delayed lookup.
    
    Parameters are the same as L{Parameter.new}.
    """
    return (args + (kwargs,))


def retval(*args, **kwargs):
    """
    Simplified syntax for representing a return value with delayed lookup.
    
    Parameters are the same as L{ReturnValue.new}.
    """
    return (args + (kwargs,))


def parse_param_spec(param_spec):
    if isinstance(param_spec, tuple):
        assert len(param_spec) >= 2
        if isinstance(param_spec[-1], dict):
            kwargs = param_spec[-1]
            args = param_spec[:-1]
        else:
            kwargs = dict()
            args = param_spec
    else:
        raise TypeError("Could not parse `%r' as a Parameter" % param_spec)
    return args, kwargs


def parse_retval_spec(retval_spec):
    if isinstance(retval_spec, tuple):
        assert len(retval_spec) >= 1
        if isinstance(retval_spec[-1], dict):
            kwargs = retval_spec[-1]
            args = retval_spec[:-1]
        else:
            kwargs = dict()
            args = retval_spec
    elif isinstance(retval_spec, str):
        kwargs = dict()
        args = (retval_spec,)
    else:
        raise TypeError("Could not parse `%r' as a ReturnValue" % retval_spec)
    return args, kwargs


def eval_param(param_value, wrapper=None):
    if isinstance(param_value, Parameter):
        return param_value
    else:
        args, kwargs = parse_param_spec(param_value)
        return call_with_error_handling(Parameter.new, args, kwargs, wrapper,
                                        exceptions_to_handle=(TypeConfigurationError,
                                                              NotSupportedError,
                                                              TypeLookupError))


def eval_retval(retval_value, wrapper=None):
    if isinstance(retval_value, ReturnValue):
        return retval_value
    else:
        args, kwargs = parse_retval_spec(retval_value)
        return call_with_error_handling(ReturnValue.new, args, kwargs, wrapper,
                                        exceptions_to_handle=(TypeConfigurationError,
                                                              NotSupportedError,
                                                              TypeLookupError))