~jc-berentsen/pidl/trunk

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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-

from emitter import Emitter
from idltype import *
from cpythonemittertemplates import *

type_to_pyformat = {
    "int" : "i",
    "string" : "s",
}

class CPythonEmitter(Emitter):
    def __init__(self, ast):
        Emitter.__init__(self, ast)

    def emit(self):
        Emitter.emit(self)

        self.cpyfilenames = ", ".join(map(lambda n: '"' + n + '"',
                                          self.source_documentnames))

        for namespace in self.namespaces:
            setup = {
                'namespace_lc': namespace.lower (),
                "cpyfilenames": [],
                "libraries": ['pme', 'taf', 'glib-2.0', 'gobject-2.0'],
                }

            filenamepattern = '^py' + namespace.lower () + '.*'
            for file in self.source_documentnames:
                if re.match(filenamepattern, file) != None:
                    setup["cpyfilenames"].append(file)
                    

            if namespace.lower() not in ['gst', 'taf', 'pme']:
                setup["libraries"].insert(0, namespace.lower ())
                        
            setupdoc = setup_tpl % setup
            setupfile = 'setup-%s.py' % namespace.lower ()
            self.documents[setupfile] = setupdoc
            
        return self.documents

    def make_module_docs (self, namespace):
        assert (self.namespace == namespace)
        addobject_lst = []
        class_enums_lst = []
        error_object_lst = []
        error_object_case_lst = []
        create_error_object_lst = []
        error_lst = self.get_errors_in_namespace (namespace)
        for error in error_lst:
            self.errorname = error
            self.errorname_uc = map_to_scored (error, uppercase=True)
            error_object_lst.append (error_object_tpl % self)
            error_object_case_lst.append (error_object_case_tpl % self)
            create_error_object_lst.append (create_error_object_tpl % self)
            addobject_lst.append (add_error_object_tpl % self)
        self.error_objects = '\n'.join (error_object_lst)
        self.error_object_cases = '\n  else '.join (error_object_case_lst)
        self.create_error_objects = '\n'.join (create_error_object_lst)

        self.error_include = ''
        self.error_raise_decl = ''
        self.error_raise_impl = ''
        if error_object_lst:
            self.error_include = '#include "%(namespace_lc)serror.h"\n' % self
            self.error_raise_decl = error_raise_decl_tpl % self
            self.error_raise_impl = error_raise_impl_tpl % self

        ready_poll_lst = []
        gtype_fwd_include_lst = []
        forward_lst = []
        signal_marshal_from_py_cases_lst = []
        for classdetails in self.classdict.iteritems ():
            idlclass = classdetails[1]

            if idlclass.is_internal or idlclass.is_external or idlclass.name.nsname != namespace:
                continue

            self.prepare_dict (classdetails)

            ready_poll_lst.append (ready_poll_tpl % self)
            forward_lst.append (module_forward_types_tpl % self)

            # skip if interface.
            if idlclass.is_interface:
                continue

            # skip if external and namespace include provided
            if idlclass.is_external:
                continue

            # Add class enums
            self.class_enums = self.make_class_enums (idlclass)
        
            addobject_lst.append (add_type_object_tpl % self)
            gtype_fwd_include_lst.append ('#include "%(filename)s.h"' % self)
            signal_marshal_from_py_cases_lst.append (signal_marshal_from_py_case_tpl % self)

        self.ready_poll = '\n\n'.join (ready_poll_lst)
        self.addobjects = '\n\n'.join (addobject_lst)
        self.gtype_fwd_includes = '\n'.join (gtype_fwd_include_lst)
        self.module_forward_types = '\n'.join (forward_lst)
        if len (signal_marshal_from_py_cases_lst) == 0:
            self.signal_marshal_from_py_cases = signal_marshal_from_py_case_last_tpl
        else:
            self.signal_marshal_from_py_cases  = '\n        else '.join (signal_marshal_from_py_cases_lst)
            self.signal_marshal_from_py_cases += '\n        else ' + signal_marshal_from_py_case_last_tpl

        base_filename = cpython_module_filename_tpl % self

        source_filename = base_filename + '.c'
        header_filename = base_filename + '.h'

        if source_filename not in self.source_documentnames:
            self.source_documentnames.append (source_filename)

        self.module_constants = module_constants_tpl % self

        docs = {
            source_filename: cpython_module_tpl % self,
            header_filename: cpython_module_header_tpl % self,
        }

        self.on_added_source_doc (source_filename)

        return docs

    def make_class_doc (self, classdetails):
        idlclass = classdetails[1]

        if idlclass.is_internal: return

        include_deps_lst_statements = []

        for ns in self.include_deps_map:
            include_deps_lst_statements.extend (map (lambda idlclassname: '#include "py%s.h"' % idlclassname,
                                            self.include_deps_map[ns]))

        include_deps_lst_statements.extend (map (lambda idlclassname: '#include "%s.h"' % idlclassname,
                                                 self.include_interface_deps_lst))

        include_deps = "\n".join(include_deps_lst_statements)

        self['include_deps'] = include_deps

        docname = cpython_class_header_filename_tpl % self
        doc = cpython_header_tpl % self
        self.documents[docname] = doc

        docname = cpython_class_filename_tpl % self
        doc = cpython_class_tpl % self
        self.documents[docname] = doc
        if docname not in self.source_documentnames:
            self.source_documentnames.append (docname)
        self.on_added_source_doc (docname)

    def on_added_source_doc (self, docname): pass

    def make_class_methods (self, classdetails):
        idl_class = classdetails[1]
        methods = idl_class.methods

        abstract_base = idl_class.get_first_abstract_base (self.classdict)

        if abstract_base:
            self.method_owner_class_name = abstract_base.name.scored_name ()
            derived_type_uc = abstract_base.name.fullname_upper ()
            self.cself_handle_casted = derived_type_uc + "(self->cself)"
        else:
            self.method_owner_class_name = self.fullname_lc
            self.cself_handle_casted = "self->cself"

        for method in methods:
            self.make_method (method, idl_class)

        self.method_defs_list = "".join(self.table)
        self.method_table = class_methods_table_tpl % self

        self.method_bodies = "".join(self.bodies)

    def make_method (self, method, idlclass):
        self.methodname = method.name
        ret_type = method.ret_type
        args = method.args
        throws = method.throws
        is_static = method.stat != ''
        is_interface = idlclass.is_interface
        if method.is_internal:
            return

        self.method_flags = "METH_VARARGS | METH_KEYWORDS"

        for arg_type,arg_name in method.args:
            self.add_include_dep(arg_type)

        if method.override:
            self.current_method_base_class_name = self.method_owner_class_name
        else:
            self.current_method_base_class_name = self.fullname_lc

        if self.methodname == 'new':
            (entry, body) = self.make_constructor(args, is_interface)
        elif self.methodname == 'del':
            (entry, body) = self.make_destructor()
        else:
            (entry, body) = self.make_method_string (method, idlclass) #ret_type, args, throws, is_static)
            self.add_include_dep(ret_type)

        self.bodies.append(body)
        self.table.append(entry)

    def make_constructor (self, args, is_interface):
        self.method_doc = "constructor..."
        self.method_brief = "constructor"
        self.argparse = self.make_arg_parse (args, False)

        self.return_declare = self.fullname + ' * result = 0;'
        self.return_capture = "result = "
        self.return_type_fmt = '"i"'
        self.return_value_cleanup = ""
        self.return_yield = return_value_tpl % self
        if is_interface:
            self.cself_init_val = "NULL"
        else:
            self.cself_init_val = cself_init_val_tpl % self

        return (class_method_def_tpl % self, class_constructor_tpl % self)

    def make_destructor(self):
        self.method_doc = "destructor..."
        self.method_brief = "destructor"
        self.argparse = self.make_arg_parse ([], False)

        self.return_declare = ''
        self.return_capture = ''
        self.return_type_fmt = ''
        self.return_value_cleanup = ""
        self.return_yield = ''

        return ('', class_destructor_tpl % self)

    def map_type(self, idl_type):
        return idl_type

    def map_types_to_format(self, arg_types):
        return [self.map_type_to_format(type) for type in arg_types]

    def map_type_to_format(self, arg_type):
        if self.is_pyobject (arg_type):
            return 'O'
        elif str(arg_type) == 'string':
            return 's'
        return 'i'

    def is_pyobject (self, arg_type):
        if arg_type and not self.is_enum_type (arg_type):
            if arg_type.nsname != '' or self.is_gobject_type (arg_type.clsname):
                return True
        return False

    def convert_arg_pair_to_c(self, arg_type, arg_cname):
        cargtype = self.type_to_c(arg_type)
        if self.is_pyobject (arg_type):
            return "Py%s %s;" % (cargtype, arg_cname)
        else:
            return "%s %s;" % (cargtype, arg_cname)

    def convert_args_to_c(self, args):
        return map(lambda (argtype, arg_cname):
                       self.convert_arg_pair_to_c(argtype, arg_cname),
                   args)

    def map_name_to_c(self, type, name):
        if self.is_object_type(type):
            return '((PyObject *) %s != Py_None) ? %s->cself : NULL' % (name, name)
        else:
            return name

    def map_args_to_c_names (self, args, is_member, ifref, override):
        names = map(lambda (type, name): self.map_name_to_c(type, name), args)

        self_prepend_lst = []

        if is_member:
            self_cself = "self->cself"
            if ifref: # implementing interface?
                self_prepend_lst = ["%s(%s)" % (ifref.fullname_upper (), self_cself)]
            else:
                if self.cself_handle_casted and override:
                    self_prepend_lst = [self.cself_handle_casted]
                else:
                    self_prepend_lst = [self_cself]

        return ", ".join(self_prepend_lst + names)

    def make_arg_parse (self, args, is_member=True, ifref=None, override=None):
        if not args:
            self.arg_names = self.map_args_to_c_names (args, is_member, ifref, override)
            # no arguments, shortcut
            #if is_member:
            #    if ifref or override: # implementing interface?
            #        self.arg_names = '%s (self->cself)' % ifref.fullname_upper ()
            #    else:
            #        self.arg_names = 'self->cself'
            #else:
            #    self.arg_names = ''
            return ''

        arg_var_lst = self.convert_args_to_c(args)

        self.arg_vars = "".join(arg_var_lst)

        arg_type_lst = map(lambda l: l[0], args)
        arg_name_lst = map(lambda l: l[1], args)

        # append ->cself if wrapped gobject!
        self.arg_names = self.map_args_to_c_names (args, is_member, ifref, override)

        self.arg_namestrings = ", ".join([ '"' + name + '"' for name in arg_name_lst])

        arg_format = "".join(self.map_types_to_format(arg_type_lst))
        self.argformat = '"' + arg_format + '"'

        self.arg_names_out = ", ".join([ "&"+name for name in arg_name_lst])

        return arg_parse_tpl % self

    def _prepare_return_value_dict(self, ret_type):
        if ret_type is None or str(ret_type) == "void":
            self.return_type_gc = ''
            self.return_declare = ''
            self.return_capture = ''
            self.return_yield = return_none_string
        else:
            self.return_type_gc = ret_type.nsname + ret_type.clsname
            self.return_declare = 'PyObject * pyresult = NULL;\n  '
            self.return_declare += self.type_to_c (ret_type) + " result = 0;"
            self.return_capture = "result = "

            type_name = str (ret_type)
            if type_name in type_to_pyformat:
                self.return_type_fmt = '"%s"' % type_to_pyformat[type_name]
            else:
                self.return_type_fmt = '"i"'

            self.return_value_cleanup = ''
            tpl = '    %s (result);\n'
            if self.is_object_type (ret_type):
                self.return_value_cleanup = return_object_cleanup_string
                self.return_yield = return_object_tpl % self
            else:
                if type_name == "string" and not ret_type.is_const:
                    self.return_value_cleanup = tpl % "g_free"

                self.return_yield = return_value_tpl % self

    def make_interface_methods(self, classdetails):
        self.bodies = []
        self.table = []
        self.include_interface_deps_lst = []

        idl_class = classdetails[1]

        self.method_owner_class_name = self.fullname_lc

        parent_methods = []
        if idl_class.base_refs:
            parent_class = self.find_idl_class (idl_class.base_refs[0]) # FIXME: support more than one interface
            parent_methods = parent_class.interface_methods
            parent_fullname = parent_class.name.nsname + parent_class.name.clsname
            self.method_owner_class_name = map_to_scored (parent_fullname, uppercase=False)
            self.include_interface_deps_lst.append (parent_class.name.nsname.lower() +
                                                    parent_class.name.clsname.lower())

            for method in parent_methods:
                self.make_interface_method (method, idl_class)

    def make_interface_method (self, method, idlclass):
        self.methodname = method.name
        #ret_type = method.ret_type
        #args = method.args
        #throws = method.throws
        #is_static = method.stat != ''

        self.method_flags = "METH_VARARGS | METH_KEYWORDS"

        for arg_type,arg_name in method.args:
            self.add_include_dep(arg_type)

        self.current_method_base_class_name = self.method_owner_class_name

        (entry, body) = self.make_method_string (method, idlclass, idlclass.base_refs[0]) #ret_type, args,
                                                 #throws, is_static, idlclass.base_refs[0])
        self.add_include_dep(method.ret_type)

        self.bodies.append(body)
        self.table.append(entry)

    def make_method_string (self, method, idlclass, ifref=None): #ret_type, args, throws, is_static, ifref=None):
        ret_type = method.ret_type
        args = method.args
        throws = method.throws
        is_static = method.stat != ''

        self.method_doc = "<no method description>"
        self.method_brief = "<no short description>"
        self.argparse = self.make_arg_parse (args, not is_static, ifref, method.override)

        self.arg_ret = ''
        if throws and (ret_type is not None and str (ret_type) != 'void'):
            self.arg_ret = ', &result'

        self._prepare_return_value_dict (ret_type)

        if is_static:
            self.method_flags += ' | METH_CLASS'

        if not throws:
            return (class_method_def_tpl % self, class_method_tpl % self)
        else:
            return (class_method_def_tpl % self, class_throwing_method_tpl % self)

    def make_signals (self, classdetails):
        self.signal_connect_body = signal_connect_tpl % self

    def make_properties(self, classdetails):
        properties=classdetails[1].props

        self.getattr_name = '0'
        self.setattr_name = '0'

        if not properties: return

        property_defs_lst = []
        get_set_method_body_lst = []
        get_prop_case_lst = []
        set_prop_case_lst = []

        for prop in properties:
            if prop.is_private: continue
            self.propname = prop.name
            self.prop_type = self.type_to_c (prop.type)
            self.propname_lc = prop.name.replace ('-', '_')
            property_defs_lst.append(get_set_property_method_table_tpl % self)

            self.add_include_dep(prop.type, False)

            self._prepare_return_value_dict(prop.type)

            args = [(prop.type, self.propname_lc) ]
            self.argparse = self.make_arg_parse (args, self)

            self.propref = '&result'
            self.propval = self.propname_lc

            if self.is_object_type (prop.type):
                self.propval = '((PyObject *) %(propname_lc)s != Py_None) ? %(propname_lc)s->cself : NULL' % self

            get_set_method_body_lst.append(get_method_implementation_tpl % self)

            self.return_yield = return_none_string
            get_set_method_body_lst.append(set_method_implementation_tpl % self)

            get_prop_case_lst.append(get_prop_cases_tpl % self)
            set_prop_case_lst.append(set_prop_cases_tpl % self)

        self.property_defs_list = "".join(property_defs_lst)
        self.get_set_method_bodies = "".join(get_set_method_body_lst)

        self.get_prop_cases = "".join(get_prop_case_lst)
        self.set_prop_cases = "".join(set_prop_case_lst)

        if not property_defs_lst:
            self.attr_methods = ''
            return

        self.getattr_name = "%(fullname_py)s_getattr" % self
        self.setattr_name = "%(fullname_py)s_setattr" % self

        self.attr_methods = "".join( (get_attr_lookup_method_tpl % self,
                                      set_attr_lookup_method_tpl % self) )

    def prepare_dict(self, classdetails):
        Emitter.prepare_dict(self, classdetails)
        self.fullname_py = "Py%(fullname)s" % self


    def make_class_enums (self, idlclass):
        class_enums_lst = []
        for enumtype in idlclass.enums:
            for enum in enumtype.enumlist:
                self.enum_full_name = self.fullname_uc + '_' + enum[0]
                self.enum_name = enum[0]
                class_enums_lst.append (class_enum_tpl % self)

        return '\n'.join (class_enums_lst)