pyobjc / pyobjc-core / Lib / PyObjCTools / _BSCompiler.py

  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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
"""
Helper script for compiling .brigesupport files into a more compact form

Note: the format of the compiled data is unstable for now, new versions
of PyObjC can and will use different formats.
"""
from __future__ import print_function

import getopt
import sys
from xml.etree import ElementTree
import time

import objc

gUsage = "Usage: pyobjc-compile-bridgesupport --input=FILE --output=FILE"

class ByteStr(str):
    __slots__ = ()

    def __repr__(self):
        result = super(ByteStr, self).__repr__()
        if result.startswith('b'):
            return result
        return 'b' + result

def bstr(s):
    if s is None:
        s = ''
    return ByteStr(s)

class funccall (object):
    def __init__(self, name, args=None, kwds=None):
        self._name = name

        self._args = ()
        self._kwds = {}

        if args is not None:
            self._args = args
        if kwds is not None:
            self._kwds = kwds

    def __call__(self, *args, **kwds):
        self._args = args
        self._kwds = kwds

    def __repr__(self):
        result = [self._name, '(']
        for a in self._args:
            if result[-1] != '(':
                result.append(', ')
            result.append(repr(a))

        for k, v in self._kwds.items():
            if result[-1] != '(':
                result.append(', ')
            result.append(k)
            result.append('=')
            result.append(repr(v))
        result.append(')')
        return ''.join(result)

def sel32or64(a, b):
    return funccall('sel32or64', (a, b))

def littleOrBig(a, b):
    return funccall('littleOrBig', (a, b))


def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'Vh?i:o:', ['version', 'help', 'input=', 'output='])

    except getopt.error as msg:
        print(msg, file=sys.stderr)
        print(gUsage, file=sys.stderr)
        sys.exit(1)

    input = None
    output = None

    if args:
        print("Additional arguments", file=sys.stderr)
        print(gUsage, file=sys.stderr)
        sys.exit(1)

    for k, v in opts:
        if k in ('-V', '--version'):
            print("pyobjc %s"%(objc.__version__,))
            sys.exit(0)

        elif k in ('-h', '-?', '--help'):
            print(gUsage)
            sys.exit(0)

        elif k in ('-i', '--input'):
            input = v

        elif k in ('-o', '--output'):
            output = v 

        else:
            raise RuntimeError("Unhandled command-line option")


    if input is None or output is None:
        print("Specify input and output files", file=sys.stderr)
        print(gUsage, file=sys.stderr)
        sys.exit(1)

    try:
        input_tree = ElementTree.parse(input)
    except Exception as msg:
        print(msg, file=sys.stderr)
        sys.exit(1)

    fp = open(output, 'w')
    print("# Generated file, don't edit", file=fp)
    print("# Source: %s"%(input,), file=fp)
    print("# Last update: %s"%(time.ctime(),), file=fp)
    print("", file=fp)
    print("import objc, sys", file=fp)
    print("", file=fp)
    print("if sys.maxsize > 2 ** 32:", file=fp)
    print("    def sel32or64(a, b): return b", file=fp)
    print("else:", file=fp)
    print("    def sel32or64(a, b): return a", file=fp)
    print("if sys.byteorder == 'little':", file=fp)
    print("    def littleOrBig(a, b): return a", file=fp)
    print("else:", file=fp)
    print("    def littleOrBig(a, b): return b", file=fp)
    print("", file=fp)

    emit_misc(fp, input_tree)
    emit_constants(fp, input_tree)
    emit_enums(fp, input_tree)
    emit_strconsts(fp, input_tree)
    emit_functions(fp, input_tree)
    emit_cftype(fp, input_tree)
    emit_classes(fp, input_tree)
    emit_informal_protocols(fp, input_tree)
    emit_null(fp, input_tree)

def rewrite_typecode(value):
    result = []

    while value and value[0] in (objc._C_PTR, objc._C_IN, objc._C_INOUT, objc._C_ONEWAY, objc._C_CONST):
        result.append(value[0])
        value = value[1:]

    if not value:
        return ''.join(result), ''

    if value[0] == objc._C_BOOL:
        result.append(objc._C_NSBOOL)
        value = value[1:]

    elif value[0] == objc._C_NSBOOL:
        result.append(objc._C_BOOL)
        value = value[1:]

    elif value[0] == objc._C_STRUCT_B:
        while value[0] != '=' and value[0] != objc._C_STRUCT_E:
            result.append(value[0])
            value = value[1:]

        if value[0] == '=':
            result.append(value[0])
            value = value[1:]

        while value[0] != objc._C_STRUCT_E:
            if value[0] == '"':
                # Embedded field name
                result.append(value[0])
                value = value[1:]
                while value[0] != '"':
                    result.append(value[0])
                    value = value[1:]
                result.append(value[0])
                value = value[1:]

            cur, value = rewrite_typecode(value)
            result.append(cur)

        result.append(objc._C_STRUCT_E)
        value = value[1:]

    elif value[0] == objc._C_UNION_B:
        while value[0] != '=' and value[0] != objc._C_UNION_E:
            result.append(value[0])
            value = value[1:]

        if value[0] == '=':
            result.append(value[0])
            value = value[1:]

        while value[0] != objc._C_UNION_E:
            if value[0] == '"':
                # Embedded field name
                result.append(value[0])
                value = value[1:]
                while value[0] != '"':
                    result.append(value[0])
                    value = value[1:]
                result.append(value[0])
                value = value[1:]

            cur, value = rewrite_typecode(value)
            result.append(cur)

        result.append(objc._C_UNION_E)
        value = value[1:]

    elif value[0] == objc._C_ARY_B:
        result.append(value[0])
        value = value[1:]
        while value[0].isdigit():
            result.append(value[0])
            value = value[1:]

        while value[0] != objc._C_ARY_E:
            cur, value = rewrite_typecode(value)
            result.append(cur)

        result.append(value[0])
        value = value[1:]

    else:
        result.append(value[0])
        value = value[1:]

    return ''.join(result), value

def rewrite_typestr(value):
    if value is None: return value
    result = []

    cur, rest = rewrite_typecode(value)
    result.append(cur)

    while rest:
        cur, rest = rewrite_typecode(rest)
        result.append(cur)
    return ''.join(result)

def emit_misc(fp, tree):
    fp.write("misc = {\n")

    for node in tree.findall('.//opaque'):
        if node.get('ignore', 'false') == 'true':
            continue
        name = node.get('name')
        type = node.get('type')
        type64 = node.get('type64')

        if type64 is None or type == type64:
            fp.write('    "%s": objc.createOpaquePointerType(%r, b%r),\n'%(
                name, name, rewrite_typestr(type)))
        else:
            fp.write('    "%s": objc.createOpaquePointerType(%r, sel32or64(b%r, b%r)),\n'%(
                name, name, rewrite_typestr(type), rewrite_typestr(type64)))

    for node in tree.findall('.//struct'):
        if node.get('ignore', 'false') == 'true':
            continue
        name = node.get('name')
        type = node.get('type')
        type64 = node.get('type64')


        if type64 is None or type == type64:
            fp.write('    "%s": objc.createStructType(%r, b%r, None),\n'%(
                name, name, rewrite_typestr(type)))
        else:
            fp.write('    "%s": objc.createStructType(%r, sel32or64(b%r, b%r), None),\n'%(
                name, name, rewrite_typestr(type), rewrite_typestr(type64)))


    fp.write("}\n")

def emit_constants(fp, tree):
    fixed = {}
    fp.write("constants = '''$")
    for node in tree.findall('.//constant'):
        if node.get('ignore', 'false') == 'true':
            continue
        name = node.get("name")
        type = rewrite_typestr(node.get("type", "@"))
        type64 = node.get("type64", None)
        if type64 is not None:
            type64 = rewrite_typestr(type64)

        if type[0] == '{':
            _, rest = type.split('=', 1)
            if '?' in rest:
                # Skip structs with embedded function pointers and
                # other unhandled types
                continue

        if type64 is not None and type64 != type:
            fixed[name] = sel32or64(type, type64)
            continue


        if node.get("magic_cookie", "false") == "true":
            type = "=" + type

        if type == "@":
            fp.write(name)
        else:
            fp.write(name)
            fp.write("@")
            fp.write(type)
        fp.write("$")
    fp.write("'''\n")
    if fixed:
        fp.write("constants_dict = %r\n"%(fixed,))


def emit_enums(fp, tree):
    others = {}
    fp.write("enums = '''$")
    for node in tree.findall('.//enum'):
        if node.get('ignore', 'false') == 'true':
            continue
        name = node.get("name")
        value = node.get("value")
        value64 = node.get("value64")

        if value is None and value64 is not None:
            value = value64


        if value is None:
            le_value = int(node.get("le_value"))
            be_value = int(node.get("be_value"))
            others[name] = littleOrBig(le_value, be_value)

        elif value64 is None or value64 == value:
            fp.write(name)
            fp.write("@")
            fp.write(value)
            fp.write("$")

        else:
            if '.' in value:
                value = float(value)
            else:
                value = int(value)

            if '.' in value64:
                value64 = float(value64)
            else:
                value64 = int(value64)


            others[name] = sel32or64(value, value64)

    fp.write("'''\n")

    if others:
        fp.write("misc.update(%r)\n"%(others,))



def emit_strconsts(fp, tree):
    items = {}
    for node in tree.findall('.//string_constant'):
        if node.get('ignore', 'false') == 'true':
            continue
        nm = node.get('name')
        value = node.get('value')
        isstr = node.get('nsstring', 'false') == 'true'
        if not isstr:
            value = value.encode('ascii')
        items[nm] = value

    print("misc.update(%s)"%(items), file=fp)

def emit_functions(fp, tree):
    items = {}
    for node in tree.findall('.//function'):
        if node.get('ignore', 'false') == 'true':
            continue

        name = node.get('name')
        types = ['v']
        types64 = ['v']
        retval = None
        arguments = []
        meta = {}

        if node.get('variadic', 'false') == 'true':
            meta['variadic'] = 'true'
            if node.get('c_array_delimited_by_null', 'false') == 'true':
                meta['c_array_delimited_by_null'] = True

            if node.get('c_array_length_in_arg') is not None:
                meta['c_array_length_in_arg'] =  \
                        int(node.get('c_array_length_in_arg'))

        for child in node:
            if child.tag == 'retval':
                retval = {}
                convert_argnode(False, child, retval)

                if child.get('type64') is not None:
                    types64[0] = rewrite_typestr(child.get('type64'))
                else:
                    types64[0] = rewrite_typestr(child.get('type'))

                types[0] = rewrite_typestr(child.get('type'))

            elif child.tag == 'arg':
                info = {}
                convert_argnode(False, child, info)
                arguments.append(info)
                
                if child.get('type64') is not None:
                    types64.append(rewrite_typestr(child.get('type64')))
                else:
                    types64.append(rewrite_typestr(child.get('type')))

                types.append(rewrite_typestr(child.get('type')))

            else:
                raise ValueError("Child node %s of function node"%(child.tag,))

        if retval is not None:
            k = list(retval.keys())
            k.sort()
            if k in (['type'], ['type', 'type64']):
                # No additional information, no need to store meta information
                pass

            else:
                meta['retval'] = retval

        if arguments:
            have_meta = False
            for a in arguments:
                k = list(a.keys())
                k.sort()
                if k in (['type'], ['type', 'type64']):
                    # No additional information, no need to store meta 
                    # information
                    pass
                else:
                    have_meta = True

            if have_meta:
                meta['arguments'] = dict(zip(range(len(arguments)), arguments))

        if meta == {}:
            meta = None

        if types[0] is None:
            types[0] = 'v'

        if types64[0] is None:
            types64[0] = 'v'


        types = bstr(''.join(types))
        types64 = bstr(''.join(types64))

        if types != types64:
            if meta is None:
                items[name] = (sel32or64(types, types64),)
            else:
                items[name] = (sel32or64(types, types64), "", meta)
        else:
            if meta is None:
                items[name] = (types,)
            else:
                items[name] = (types, "", meta)


    fp.write("functions = %r\n"%(items,))


BOOLEAN_ATTRIBUTES=[
    ("already_retained", False),
    ("already_cfretained", False),
    ("c_array_length_in_result", False),
    ("c_array_delimited_by_null", False),
    ("c_array_of_variable_length", False),
    ("printf_format", False),
    ("free_result", False),
    ("null_accepted", True),
]

def parse_callable(isfunction, node, dct):
    if node.get('function_pointer_retained', 'true') == 'false':
        dct['callable_retained'] = False

    meta = dct['callable'] = {}
    meta['arguments'] = arguments = {}
    idx = 0

    if not isfunction:
        # Blocks have an implicit first argument
        arguments[idx] = {
                'type': '^v',
        }
        idx += 1

    for child in node:
        if child.tag == 'retval':
            retval = meta['retval'] = {}
            convert_argnode(False, child, retval)

        elif child.tag == 'arg':
            info = {}
            convert_argnode(False, child, info)
            arguments[idx] = info
            idx += 1

        else:
            raise ValueError("Child node %s of function node"%(child.tag,))

    if meta.get('retval') is None:
        meta['retval'] = {
            'type': 'v',
        }

        

def convert_argnode(ismethod, node, dct):
    if ismethod:
        argoffset = 2
    else:
        argoffset = 0

    v = node.get('type_modifier')
    if v is not None:
        dct['type_modifier'] = bstr(v)

    type = node.get('type')
    type64 = node.get('type64')
    if type is not None:
        if type64 is None or type == type64:
            dct['type'] = bstr(rewrite_typestr(type))
        else:
            dct['type'] = sel32or64(
                    bstr(rewrite_typestr(type)),
                    bstr(rewrite_typestr(type64)))

    sel_of_type = node.get('sel_of_type')
    sel_of_type64 = node.get('sel_of_type64')
    if sel_of_type is not None:
        if sel_of_type64 is None or sel_of_type == sel_of_type64:
            dct['sel_of_type'] = bstr(rewrite_typestr(sel_of_type))
        else:
            dct['sel_of_type'] = sel32or64(
                    bstr(rewrite_typestr(sel_of_type)),
                    bstr(rewrite_typestr(sel_of_type64)))

    v = node.get('c_array_of_fixed_length')
    if v is not None:
        dct['c_array_of_fixed_length'] = int(v)


    v = node.get('c_array_length_in_arg')
    if v is not None:
        if ',' in v:
            a, b = v.split(',')
            a = a.strip()
            b = b.strip()

            dct['c_array_length_in_arg'] = int(a)+argoffset, int(b)+argoffset
        else:
            dct['c_array_length_in_arg'] = int(v)+argoffset


    v = node.get('function_pointer')
    if v == 'true':
        parse_callable(True, node, dct)

    v = node.get('block')
    if v == 'true':
        parse_callable(False, node, dct)


    for attr, default in BOOLEAN_ATTRIBUTES:
        v = node.get(attr)
        if v is not None:
            if v == 'true':
                v = True
            else:
                v = False

            if v != default:
                dct[attr] = v


def emit_classes(fp, tree):
    print("r = objc.registerMetaDataForSelector", file=fp)
    print("objc._updatingMetadata(True)", file=fp)
    print("try:", file=fp)
    print("    pass", file=fp)
    for node in tree.findall('.//class'):
        if node.get('ignore', 'false') == 'true':
            continue
        clsname = node.get('name')
        for method in node:
            if method.tag != 'method': continue

            if method.get('ignore', 'false') == 'true':
                continue
            sel = bstr(method.get('selector'))
            meta = {}
            if method.get('variadic', 'false') == 'true':
                meta['variadic'] = 'true'
                if method.get('c_array_delimited_by_null', 'false') == 'true':
                    meta['c_array_delimited_by_null'] = True

                if method.get('c_array_length_in_arg') is not None:
                    meta['c_array_length_in_arg'] =  \
                            int(node.get('c_array_length_in_arg'))
            for info in method:
                if info.tag == 'retval':
                    n = meta['retval'] = {}
                elif info.tag == 'arg':
                    if 'arguments' not in meta:
                        meta['arguments'] = {}

                    n = meta['arguments'][int(info.get('index'))+2] = {}

                convert_argnode(True, info, n)

            print('    r(%r, %r, %r)'%(bstr(clsname), sel, meta), file=fp)

    print("finally:", file=fp)
    print("    objc._updatingMetadata(False)", file=fp)

def emit_cftype(fp, tree):
    print("cftypes = []", file=fp)
    for node in tree.findall('.//cftype'):
        name = node.get('name')
        type = bstr(node.get('type'))
        type64= bstr(node.get('type64'))
        if type64 is not None and type64 != type:
            type = sel32or64(type, type64)

        gettypeid_func = node.get('gettypeid_func')
        tollfree= node.get('tollfree')

        print("cftypes.append((%r, %r, %r, %r))"%(name, type, gettypeid_func, tollfree), file=fp)




def prot(name, methods):
    return funccall('objc.informal_protocol', (name, methods))

def sel(selector, type):
    return funccall('objc.selector', (None, selector, type), {'isRequired': False})

def emit_informal_protocols(fp, tree):
    protocols = {
    }
    for node in tree.findall('.//informal_protocol'):
        name = node.get('name')

        methods = []

        for method in node:
            selector = bstr(method.get('selector'))
            type = bstr(rewrite_typestr(method.get('type')))
            type64 = bstr(rewrite_typestr(method.get('type64')))

            if type64 and type != type64:
                type = sel32or64(type, type64)

            methods.append(sel(selector, type))

        protocols[name] = prot(name, methods)

    if protocols:
        fp.write('protocols=%s\n'%(protocols))

def emit_null(fp, tree):
    values = {}
    for node in tree.findall('.//null_const'):
        name = node.get('name')
        values[name] = None

    if values:
        fp.write('misc.update(%r)'%(values,))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.