1 ! Copyright (C) 2006 Slava Pestov
2 ! See http://factorcode.org/license.txt for BSD license.
4 USING: alien arrays compiler hashtables kernel kernel-internals
5 libc math namespaces sequences strings words ;
7 : init-method ( method alien -- )
9 [ >r execute r> set-objc-method-imp ] keep
10 [ >r <malloc-string> r> set-objc-method-types ] keep
11 >r sel_registerName r> set-objc-method-name ;
13 : <empty-method-list> ( n -- alien )
14 "objc-method-list" c-size
15 "objc-method" c-size pick * + 1 calloc
16 [ set-objc-method-list-count ] keep ;
18 : <method-list> ( methods -- alien )
19 dup length dup <empty-method-list> -rot
20 [ pick method-list@ objc-method-nth init-method ] 2each ;
22 : <method-lists> ( methods -- lists )
23 <method-list> alien-address
24 "void*" <malloc-object> [ 0 set-alien-unsigned-cell ] keep ;
26 : <objc-class> ( name info -- class )
27 "objc-class" <malloc-object>
28 [ set-objc-class-info ] keep
29 [ >r <malloc-string> r> set-objc-class-name ] keep ;
31 ! The Objective C object model is a bit funny.
32 ! Every class has a metaclass.
34 ! The superclass of the metaclass of X is the metaclass of the
37 ! The metaclass of the metaclass of X is the metaclass of the
39 : meta-meta-class ( class -- class ) root-class objc-class-isa ;
41 : copy-instance-size ( class -- )
42 dup objc-class-super-class objc-class-instance-size
43 swap set-objc-class-instance-size ;
45 : <meta-class> ( methods superclass name -- class )
47 [ >r dup objc-class-isa r> set-objc-class-super-class ] keep
48 [ >r meta-meta-class r> set-objc-class-isa ] keep
49 [ >r <method-lists> r> set-objc-class-methodLists ] keep
50 dup copy-instance-size ;
52 : <new-class> ( methods metaclass superclass name -- class )
53 CLS_CLASS <objc-class>
54 [ set-objc-class-super-class ] keep
55 [ set-objc-class-isa ] keep
56 [ >r <method-lists> r> set-objc-class-methodLists ] keep
57 dup copy-instance-size ;
59 : (define-objc-class) ( imeth cmeth superclass name -- )
60 >r objc-class r> [ <meta-class> ] 2keep <new-class>
63 : encode-types ( return types -- encoding )
65 [ [ alien>objc-types get hash % CHAR: 0 , ] each ] "" make ;
67 : struct-return ( ret types quot -- ret types quot )
69 pick c-size [ memcpy ] curry append
70 >r { "void*" } swap append >r drop "void" r> r>
73 : prepare-method ( ret types quot -- type imp )
74 >r [ encode-types ] 2keep r>
75 [ struct-return 3array % \ alien-callback , ] [ ] make
78 : prepare-methods ( methods -- methods )
79 [ first4 prepare-method 3array ] map ;
81 : define-objc-class ( superclass name imeth cmeth -- )
83 [ prepare-methods ] 2apply
84 [ 2array % 2array % \ (define-objc-class) , ] [ ] make
85 r> swap import-objc-class ;