Source

pyobjc / sandbox / parsing / tokenize_header.py

Full commit
  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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
from scanner import *
from textwrap import dedent
import re

TYP_PTR = re.compile(r'\s+\*')
SPACE_NORMALIZE = re.compile(r'\s+')

#type mapping 'const unsigned char *   ConstStringPtr' -> 'unsigned char* ConstStringPtr'
#type mapping 'unsigned char           Str255[256]' -> 'unsigned char Str255[256]'
#type mapping 'const unsigned char *   ConstStr255Param' -> 'unsigned char* ConstStr255Param'
def normalize_type(typ, _memoize={}):
    try:
        return _memoize[typ]
    except KeyError:
        pass
    orig = typ
    # XXX: Technically const could be turned into objc._C_CONST but
    #      I can't imagine how that would make a difference.
    for skip in ('const',):
        if typ.startswith(skip + ' '):
            typ = typ[len(skip)+1:]
        typ = typ.replace(' ' + skip + ' ', ' ')
    typ = TYP_PTR.sub('*', typ)
    typ = SPACE_NORMALIZE.sub(' ', typ)
    typ = typ.strip()
    #if orig != typ:
    #    print 'type mapping %r -> %r' % (orig, typ)
    _memoize[orig] = typ
    return typ

SUBPATTERNS = dict(
    AVAILABLE=r'([A-Z][A-Z0-9_]+)',
    PROTOCOLS=r'(<[^>]+>)',
    TYPE_KEYWORD=r'((unsigned|long|char|volatile|inline|__(\w+?)__|const))',
    KEYWORD=r'((double|float|int|unsigned|long|char|extern|volatile|void|inline|__(\w+?)__|const|typedef|static))',
    IDENTIFIER=r'((?!const|volatile)[A-Za-z_]\w*)',
    SIZEOF=r'(sizeof\(([^)]+)\))',
    DECIMAL=r'([+\-]?((\.\d+)|(\d+(\.\d*)?))([eE]\d+)?[fF]?)',
    INTEGER=r'([+\-]?\d+[uU]?[lL]?[lL]?)',
    CHARS=r"('([^\\'\n]|\\')*')",
    STRING=r'("([^\\"\n]|\\")*")',
    CFSTRING=r'(CFSTR\("([^\\"\n]|\\")*"\))',
    HEX=r'(0[xX][0-9a-fA-F]+[uU]?[lL]?)',
    EXTERN=r'((([A-Z-a-z_]\w*?_)?(EXTERN|EXPORT)|extern))',
    EXPORT=r'((([A-Z-a-z_]\w*?_)?(EXPORT|EXTERN)|extern))',
    STATIC_INLINE=r'((([A-Z-a-z_]\w*?_)?INLINE|static\s+inline|static\s+__inline__))',
    BRACES=r'(([^\n}]*|([^}][^\n]*\n)*))',
    INDIRECTION=r'(\s*\*)',
    BOL=r'(\s*^\s*)',
    EOL=r'(\s*$\n?)',
    OPERATORS=r'(\||\+|-|\*|&|>>|<<|\^)',
)

WEIRD_INTEGER = re.compile(r'(0[xX][0-9a-fA-F]+|[0-9]+)[uUlL]+')
def cleanup_text(s):
    return WEIRD_INTEGER.sub(r'\1L', s.replace('\t', '        '))

def deadspace(string, begin, end):
    return 'NO MATCH FOR [%d:%d] %r' % (begin, end, string[begin:end])

def pattern(s):
    return dedent(s).strip() % SUBPATTERNS

def example(s):
    return dedent(s).strip()

class CPPDecls(Token):
    pattern = pattern(r'''
    (__BEGIN_DECLS|__END_DECLS)
    ''')

class CPPCrap(Token):
    pattern = pattern(r'''
    \#\s*(
        if\s*defined\s*\(\s*__cplusplus\s*\)
        | ifdef\s*__cplusplus
    )
    (?P<body>
        [^#]*
        (
            \#if[^#]*
            (
                (?!\#\s*endif)
                \#
                [^#]*
            )*
            \#\s*endif[^#]*

          |
            (?!\#\s*endif)
            \#
            [^#]*
        )*
    )
    \#\s*endif
    ''')
    example = example('''
    #if defined(__cplusplus)
    extern "C" {
    #endif
    #if defined(__cplusplus)
    }
    #endif
    #ifdef __cplusplus
    sucktastic
    #define foo
    #endif
    ''')

class BlockComment(Token):
    # Note: we use non-greedy matching instead of spelling out that the
    # contents of a comment cannot contain '*/' because we ran into 
    # limitation of the regexp-engine when parsing files with very big
    # comments, such as in SystemConfiguration.framework
    pattern = pattern(r'''
    \/\*
    (?P<comment>.*?)
    \*\/
    ''')
    example = example('''
    /*************\t\tThis is an annoying one\t\t**********/
    /* this is a block comment */
    ''')
    # The really nasty one is this:
    # /* foo \*/ bar */
    # Don't worry about it until we see this in real headers

class SingleLineComment(Token):
    pattern = pattern(r'//(?P<comment>[^\n]*)(\n|$)')
    example = example(r'// this is a single line comment')

class OpaqueNamedStruct (Token):
    pattern = pattern(r'''
    typedef\s+(?P<const>const\s+)?struct\s+
    (?P<label>%(IDENTIFIER)s)\s*
    (?P<indirection>(\s|\*)+)
    \s*
    (?P<name>%(IDENTIFIER)s)\s*
    ;
    ''')
    
    example = example('''
    typedef struct _Foo Foo;
    typedef struct _Bar *BarRef;
    ''')

class UninterestingTypedef(Token):
    pattern = pattern(r'''
    typedef
    \s*(?P<body>[^;]*)
    ;
    ''')
    example = example('''
    typedef baz wibble fun* SomethingGreat;
    ''')

class CompilerDirective(Token):
    pattern = pattern(r'''
    \#\s*(?P<name>undef|if|ifdef|ifndef|endif|else|elif|pragma|error|warn|define)
    [ \t]*(?P<body>([^\\\n]|\\(\n|$))*)
    ''')
    example = example(r'''
    #if defined(foo)
    #if \
        insane
    #endif
    #else stuff
    #define NS_DURING { \
        GARBAGE!  blah blah {
    ''')

class Interface(Token):
    pattern = pattern(r'''
    @interface
        \s+(?P<name>%(IDENTIFIER)s)
        \s*(?:\((?P<category>%(IDENTIFIER)s)\))?
        \s*(?::\s*(?P<super>%(IDENTIFIER)s))?
        \s*(?:<(?P<protocols>[^>]*)>)?
        \s*(?:{(?P<ivars>%(BRACES)s)})?
        \s*(?P<interface_body>.*?)
    @end
    ''')
    example = example(r'''
    @interface Foo(Bar): Baz <protocols> {
    @private
        NSArray *crazy;
    }

    + (Foo *)newFoo;
    - init;
    @end
    ''')

class Protocol(Token):
    pattern = pattern(r'''
    @protocol
        \s+(?P<name>%(IDENTIFIER)s)
        \s*(?:<(?P<super>%(IDENTIFIER)s)>)?
        \s*(?P<protocol_body>.*?)
    @end
    ''')
    example = example(r'''
    @protocol FooProtocol <Foo>
    + (Foo *)protoFoo;
    @end
    ''')

class AngleImport(Token):
    pattern = pattern(r'''
    \#\s*(?P<import_type>import|include)
        \s+<(?P<import_file>[^>]*)>
    ''')
    example = example('#import <Foo/Bar.h>')

class StringImport(Token):
    pattern = pattern(r'''
    \#\s*(?P<import_type>import|include)
        \s+"(?P<import_file>[^"]*)"
    ''')
    example = example('#import "Foo/Bar.h"')

class SimpleDefine(Token):
    #XXX ((type)foo)
    pattern = pattern(r'''
    \#\s*define\s*
        (?P<name>%(IDENTIFIER)s)\s+
        \(?
            (?P<value>
                (?!%(KEYWORD)s)
                (
                    %(CFSTRING)s
                    | %(CHARS)s
                    | %(STRING)s
                    | %(SIZEOF)s
                    | %(DECIMAL)s
                    | (
                        %(HEX)s
                        | %(INTEGER)s
                        | %(IDENTIFIER)s
                        | %(OPERATORS)s
                        | [ \t]+
                      )+
                )
            )
        \)?
        (?!
            [ \t]*[^/\n \t]
        )
    ''')
    example = example(r'''
    #define foo bar | baz
    #define foo bar << 1234
    #define foo (bar | baz)
    #define foo (bar | 0xFFF)
    #define foo 'foo!'
    #define foo bar
    #define foo 0x200
    #define foo 2.0
    #define foo "foo"
    #define foo CFSTR("foo")
    #define foo sizeof(bar)
    #define foo (8)
    ''')
    
class FunctionCallDefine(Token):
    pattern = pattern(r'''
    \#\s*define\s*
        (?P<name>%(IDENTIFIER)s)
        [ \t]*
        (?P<body>
            %(IDENTIFIER)s
            [ \t]*
            \(
                [^)]*
            \)
            [ \t]*
        )
    (\n|$)
    ''')
    example = example(r'''
    #define IUnknownUUID CFUUIDGetConstantUUIDWithBytes(NULL, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46)
    ''')

class MacroDefine(Token):
    pattern = pattern(r'''
    \#\s*define\s*
        (?P<name>%(IDENTIFIER)s)
        \(
            (?P<args>
                (\s*%(IDENTIFIER)s\s*,)*
                (\s*%(IDENTIFIER)s\s*)?
            )
        \)
    \s*(?P<body>([^\\\n]|\\(\n|$))*)
    ''')
    example = example(r'''
    #define NSLocalizedString(key, comment) \
        [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]
    #define GetNSApp() [NSApplication sharedApplication]
    #define DoStuff(a, b, c) do { \
        blah blah blah \
        blah blah blah \
    } while (0);
    ''')

class GlobalThing(Token):
    pattern = pattern(r'''
    (?:%(EXTERN)s|%(EXPORT)s)\s+
    (const\s+)?
    (?P<type>%(IDENTIFIER)s%(INDIRECTION)s*)
    \s*(const\s+)?
    (?P<name>
        %(IDENTIFIER)s
        (
            \s*,\s*
            %(INDIRECTION)s*
            \s*(const\s+)?
            %(IDENTIFIER)s
        )*
    )
    (?:\s*\[\s*\]\s*|\b)
    (
        (\s*//(?P<comment>[^\n]*)(\n|$))?
        (?:\s+%(AVAILABLE)s)
    )?
    ;
    ''')
    example = example(r'''
    extern const double FooBar;
    extern const NSString *foo;
    extern NSString *foo;
    APPKIT_EXTERN NSString* const foo;
    APPKIT_EXTERN NSString* const foo // argh a comment
        AVAILABLE_SOMEWHERE;
    FOUNDATION_EXPORT NSString * const Foo;
    extern CFStringRef cfFoo AVAILABLE_MAC_OSX_10_8;
    APPKIT_EXTERN const char foosball[] AVAILABLE_NEVER;
    ''')

class ForwardClassReference(Token):
    pattern = pattern(r'@class (?P<name>[^;]+);')
    example = example(r'@class Foo;')

class EnumBareMember(Token):
    pattern = pattern(r'''
    \s*(?P<name>%(IDENTIFIER)s)
    \s*,?
    ''')
    example = example(r'''
    Foo,
    Foo
    ''')

class EnumValueMember(Token):
    pattern = pattern(r'''
    \s*(?P<name>%(IDENTIFIER)s)
    \s*=
    \s*(?P<value>(
        \(?
        (
            %(CHARS)s
            | (
                %(HEX)s
                | %(INTEGER)s
                | %(IDENTIFIER)s
                | %(OPERATORS)s
                | \s+
              )+
        )
        \)?
        ))
    \s*,?
    ''')
    example = example(r'''
    NSXMLNodePreserveQuotes = (NSXMLNodeUseSingleQuotes | NSXMLNodeUseDoubleQuotes),
    NSXMLNodePreserveCharacterReferences = 1 << 27,
    Foo = 12,
    Foo = 2
    ''')

class NamedEnumEnd(Token):
    pattern = pattern(r'''
    \s*}
    \s*(?P<name>%(IDENTIFIER)s)
    \s*;
    ''')
    example = example(r'''
    } FooBarBazWible;
    ''')

class NamedEnum(ScanningToken):
    pattern = pattern(r'''
    typedef
    \s+enum
    \s*(?P<name>%(IDENTIFIER)s)?
    \s*{\s*
    ''')
    endtoken = NamedEnumEnd
    lexicon = [
        CompilerDirective,
        InsignificantWhitespace,
        BlockComment,
        SingleLineComment,
        EnumValueMember,
        EnumBareMember,
    ]
    example = example(r'''
    typedef enum {
        FooBar = 1, // This is the best value for FooBar
        Baz = 2,
        Wibble
    } FooBarBazWibble;
    typedef enum {
        FooBar, /* But this FooBar has no value! */
        Baz,
        Wibble
    } FooBarBazWibble;
    ''')

class EnumEnd(Token):
    pattern = pattern(r'''
    \s*}
    \s*;
    ''')
    example = example(r'''
    };
    ''')

class UninterestingStruct(Token):
    # XXX handle comments? need its own internal parser?
    pattern = pattern(r'''
    struct[^{;]+;
    ''')
    example = example(r'''
    struct Foo;
    struct Foo Bar;
    ''')

 
class Struct(Token):
    # XXX handle comments? need its own internal parser?
    pattern = pattern(r'''
    (struct|union)
    \s*(?P<structname>%(IDENTIFIER)s)?
    \s*{
        (?P<content>%(BRACES)s)
    }
    (\s*%(AVAILABLE)s)?
    \s*;
    ''')
    example = example(r'''
    struct {
        signed foo name;
        int bar;
    };
    struct _FooBarStruct {
        signed foo name;
        int bar;
    };
    ''')

class NamedStructEnd(Token):
    pattern = pattern(r'''
    \s*}
    \s*(?P<name>%(IDENTIFIER)s)
    (\s*%(AVAILABLE)s)?
    \s*;
    ''')
    example = example(r'''
        } FooBarBazWible;
        } FooBar AVAILABLE_MAC_OS_X_10_3_AND_LATER;
    ''')


class FunctionStructMember(Token):
    pattern = pattern(r'''
    \s*(?P<returns>%(IDENTIFIER)s%(INDIRECTION)s*)
    \s*\(\s*\*\s*%(IDENTIFIER)s\s*\)
    \(
        (?P<args>\s*[^)]*)
    \);
    ''')
    example = example(r'''
        void* (*pfunc)(int, float);
    ''')

class NestedStructMember(Token):
    pattern = pattern(r'''
    \s*(union|struct)\s+(?P<structname>%(IDENTIFIER)s)?
    \s*{\s*
        (?P<body>[^}]*)
    }\s+(?P<name>%(IDENTIFIER)s)\s*;
    ''')
    example=example('''
    union {
        int a;
        int b;
    } c;
    union foo {
        int my;
        int thy;
    } foo;
    struct {
        int foo;
        int bar;
    } bar;
    ''')

class StructMember(Token):
    pattern = pattern(r'''
    (const\s+)?
    (?P<type>%(IDENTIFIER)s%(INDIRECTION)s*)
    \s*(const\s+)?
    (?P<name>
        %(IDENTIFIER)s
        (
            \s*,\s*
            %(INDIRECTION)s*
            \s*(const\s+)?
            %(IDENTIFIER)s
        )*
    )
    (?:\s*\[\s*\]\s*|\b)
    (
        (\s*//(?P<comment>[^\n]*)(\n|$))?
        (?:\s+%(AVAILABLE)s)
    )?
    ;
    ''')
    example = example(r'''
    const double FooBar;
    const NSString *foo;
    NSString *foo;
    NSString* const foo;
    NSString* const foo // argh a comment
        AVAILABLE_SOMEWHERE;
    NSString * const Foo;
    CFStringRef cfFoo AVAILABLE_MAC_OSX_10_8;
    const char foosball[] AVAILABLE_NEVER;
    ''')

class NamedStruct(ScanningToken):
    # XXX handle comments? need its own internal parser?
    pattern = pattern(r'''
    typedef
    \s+(?P<structtype>(struct|union))
    \s*(?P<structname>%(IDENTIFIER)s)?
    \s*{\s*
    ''')
    endtoken = NamedStructEnd
    lexicon = [
        CompilerDirective,
        NestedStructMember,
        FunctionStructMember,
        StructMember,
    ]
    example = example(r'''
    typedef struct { } NSEmptyStruct;
    typedef struct {unsigned long v;} NSSwappedFloat;
    typedef struct { int bar; } FooBar;
    typedef struct {
        signed foo name;
        int bar;
    } FooBarStruct;
    typedef struct _FooBarStruct {
        signed foo name;
        int bar;
    } FooBarStruct;
    typedef struct _FooBarStruct {
        signed foo name;
        union {
            int stuff;
        } foo;
        int bar;
    } FooBarStruct;
    typedef struct {
        int (*pfunc)(void);
    } FunctionStruct;
    ''')
 
class Enum(ScanningToken):
    pattern = pattern(r'''
    \s*enum
    \s*(?P<name>%(IDENTIFIER)s)?
    \s*{\s*
    ''')
    endtoken = EnumEnd
    lexicon = [
        CompilerDirective,
        InsignificantWhitespace,
        BlockComment,
        SingleLineComment,
        EnumValueMember,
        EnumBareMember,
    ]
    example = example(r'''
    enum {
        FooBar = 1, // This is the best value for FooBar
        Baz = 2,
        Wibble
    };
    enum {
        FooBar, /* But this FooBar has no value! */
        Baz,
        Wibble
    };
    ''')

class FunctionEnd(Token):
    pattern = pattern(r'''
    \)
    (\s*(?P<available>%(AVAILABLE)s))?
    \s*;
    ''')
    example = example(r'''
    );
    )  ;
    ) AVAILABLE_SOMEHOW;
    ''')

class FunctionParameter(Token):
    pattern = pattern(r'''
    \s*(?P<type>
        (%(KEYWORD)s\s+)*
        %(IDENTIFIER)s\s*
        (%(INDIRECTION)s|\s+%(KEYWORD)s)*
        \s*
        (?<=\*|\s)
    )\s*
    (?P<name>%(IDENTIFIER)s\s*)?\s*,?
    ''')
    example = example(r'''
    NSString* foo
    NSString *foo, NSString *bar
    CFDataRef ref
    ''')

class FunctionElipsisParameter (Token):
    pattern = pattern(r'''\s*\.\.\.\s*''')
    example = example(r'''...''')

class ExportVoidFunction (Token):
    pattern = pattern(r'''
    %(EXPORT)s?
    \s*(?P<returns>
        (%(TYPE_KEYWORD)s(\s+%(TYPE_KEYWORD)s)*)??
        \s*%(IDENTIFIER)s
        ((\s|\*)(\s*(\*|%(KEYWORD)s))*\s*(?<=\s|\*))?
    )
    (\s*(?P<protocols>%(PROTOCOLS)s)\s*)?
    \s*(\/\*.*?\*\/)?\s*
    (\s%(IDENTIFIER)s\s)?
    \s*(?P<name>%(IDENTIFIER)s)
    \s*\(\s*void\s*\)
    (\s*(?P<available>%(AVAILABLE)s))?;''')


class ExportFunction(ScanningToken):
    pattern = pattern(r'''
    %(EXPORT)s?
    \s*(?P<returns>
        (%(TYPE_KEYWORD)s(\s+%(TYPE_KEYWORD)s)*)??
        \s*%(IDENTIFIER)s
        ((\s|\*)(\s*(\*|%(KEYWORD)s))*\s*(?<=\s|\*))?
    )
    (\s*(?P<protocols>%(PROTOCOLS)s)\s*)?
    \s*(\/\*.*?\*\/)?\s*
    (\s%(IDENTIFIER)s\s)?
    \s*(?P<name>%(IDENTIFIER)s)
    \s*\(
    ''')
    endtoken = FunctionEnd
    lexicon = [
        InsignificantWhitespace,
        FunctionElipsisParameter,
        FunctionParameter,
    ]
    example = example(r'''
    extern NSString *ABLocalizedPropertyOrLabel(NSString *propertyOrLabel);
    APPKIT_EXTERN NSString *NSSomething(NSString *arg, NSString *arg)
        AVAILABLE_SOMEWHERE;
    FOUNDATION_EXPORT void *NSSomething(unsigned long arg, unsigned long arg) AVAILABLE_SOMEWHERE;
    FOUNDATION_EXPORT SomeResult <NSObject> SomeName(const Foo *, const Foo *Bar);
    FOUNDATION_EXPORT SomeResult **SomeName(const Foo *, const Foo *Bar);
    FOUNDATION_EXPORT SomeResult SomeName(int,float);
    CFArrayRef /* of SCFoo's */ SCNetworkInterfaceCopyAll    (void) AVALABLE_FOO;
    CF_EXPORT
    const UInt8 *CFDataGetBytePtr(CFDataRef theData);
    NPError NP_LOADSS   NP_New(void);
    ''')

#!# class ExportFunction(Token):
#!#     # XXX handle comments? need its own internal parser?
#!#     pattern = pattern(r'''
#!#     %(EXPORT)s?
#!#     \s*(?P<returns>
#!#         (%(KEYWORD)s\s*)*
#!#         %(IDENTIFIER)s
#!#         (%(INDIRECTION)s|\s+%(KEYWORD)s)*
#!#     )
#!#     (\s*(?P<protocols>%(PROTOCOLS)s))?
#!#     \s*(?P<name>%(IDENTIFIER)s)
#!#     \s*\(
#!#         (?P<args>\s*[^)]*)
#!#     \s*\)
#!#     (\s*(?P<available>%(AVAILABLE)s))?
#!#     \s*;
#!#     ''')
#!#     example = example(r'''
#!#     APPKIT_EXTERN NSString *NSSomething(NSString *arg, NSString *arg)
#!#         AVAILABLE_SOMEWHERE;
#!#     FOUNDATION_EXPORT void *NSSomething(unsigned long arg, unsigned long arg) AVAILABLE_SOMEWHERE;
#!#     FOUNDATION_EXPORT SomeResult <NSObject> SomeName(const Foo *, const Foo *Bar);
#!#     FOUNDATION_EXPORT SomeResult **SomeName(const Foo *, const Foo *Bar);
#!#     FOUNDATION_EXPORT SomeResult SomeName(int,float);
#!#     ''')

class StaticInlineFunction(Token):
    # XXX need to figure out how to find a close brace
    #     will probably need something stateful I guess
    pattern = pattern(r'''
    %(STATIC_INLINE)s
    \s*(?P<returns>
        (%(KEYWORD)s\s*)*
        %(IDENTIFIER)s
        (%(INDIRECTION)s|\s+%(KEYWORD)s)*
    )
    \s*(?P<name>%(IDENTIFIER)s)
    \s*\(
        (?P<args>\s*[^)]*)
    \s*\)
    \s*{
        (?P<body>%(BRACES)s)
    }
    ''')
    example = example(r'''
    static inline unsigned int NSEventMaskFromType(NSEventType type) { return (1 << type); }
    FOUNDATION_STATIC_INLINE BOOL NSDecimalIsNotANumber(const NSDecimal *dcm)
      { return ((dcm->_length == 0) && dcm->_isNegative); }
    FOUNDATION_STATIC_INLINE unsigned short NSSwapShort(unsigned short inv) {
        return CFSwapInt16(inv);
    }
    FOUNDATION_STATIC_INLINE NSSwappedFloat NSConvertHostFloatToSwapped(float x) {
        union fconv {
        float number;
        NSSwappedFloat sf;
        };
        return ((union fconv *)&x)->sf;
    }
    ''')


LEXICON = [
    InsignificantWhitespace,
    BlockComment,
    SingleLineComment,
    Interface,
    Protocol,
    AngleImport,
    StringImport,
    FunctionCallDefine,
    SimpleDefine,
    GlobalThing,
    ForwardClassReference,
    NamedEnum,
    Enum,
    NamedStruct,
    Struct,
    MacroDefine,
    CPPDecls,
    CPPCrap,
    CompilerDirective,
    OpaqueNamedStruct,
    UninterestingTypedef,
    StaticInlineFunction,
    ExportVoidFunction,
    ExportFunction,
    UninterestingStruct,
]

if __name__ == '__main__':
    from pdb import pm
    import re
    import sys
    frameworks = """
    SystemConfiguration
    AddressBook
    AppKit
    ExceptionHandling
    Foundation
    InterfaceBuilder
    Message
    PreferencePanes
    ScreenSaver
    SecurityInterface
    WebKit
    CoreFoundation
    AppKitScripting
    ApplicationServices
    Cocoa
    DirectoryService
    DiscRecording
    DiscRecordingUI
    LDAP
    Scripting
    SecurityFoundation
    SecurityInterface
    System
    SystemConfiguration
    Security
    Carbon
    CoreServices
    """.split()
    files = sys.argv[1:]
    if not files:
        import glob
        for framework in frameworks:
            if framework.startswith('#'):
                continue
            files.extend(glob.glob('/System/Library/Frameworks/%s.framework/Headers/*.h' % (framework,)))
    fn = None
    def deadraise(string, i, j):
        print '-' * len(fn)
        print fn
        print '-' * len(fn)
        s = string[i:].split('\n',1)[0]
        print s
        print
        import pdb
        pdb.Pdb().set_trace()
    scan = Scanner(LEXICON)
    for fn in files:
        print '-' * len(fn)
        print fn
        print '-' * len(fn)
        for token in scan.iterscan(file(fn).read(), dead=deadraise):
            if token is not None:
                print token