1 ! Copyright (C) 2008, 2009 Slava Pestov, Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien alien.c-types alien.parser
4 alien.libraries arrays assocs classes combinators
5 combinators.short-circuit compiler.units effects grouping
6 kernel parser sequences splitting words fry locals lexer
7 namespaces summary math vocabs.parser ;
10 : parse-c-type-name ( name -- word )
11 dup search [ ] [ no-word ] ?if ;
13 : parse-c-type ( string -- type )
15 { [ dup "void" = ] [ drop void ] }
16 { [ CHAR: ] over member? ] [ parse-array-type parse-c-type-name prefix ] }
17 { [ dup search c-type-word? ] [ parse-c-type-name ] }
18 { [ "**" ?tail ] [ drop void* ] }
19 { [ "*" ?tail ] [ parse-c-type-name resolve-pointer-type ] }
20 [ dup search [ no-c-type ] [ no-word ] ?if ]
23 : scan-c-type ( -- c-type )
25 [ drop \ } parse-until >array ]
28 : reset-c-type ( word -- )
29 dup "struct-size" word-prop
30 [ dup [ forget-class ] [ { "struct-size" } reset-props ] bi ] when
38 : CREATE-C-TYPE ( -- word )
39 scan current-vocab create {
46 : normalize-c-arg ( type name -- type' name' )
49 [ CHAR: * = ] trim-head
50 [ length - CHAR: * <array> append ] keep
52 [ parse-c-type ] dip ;
54 : parse-arglist ( parameters return -- types effect )
56 2 group [ first2 normalize-c-arg 2array ] map
57 unzip [ "," ?tail drop ] map
59 [ [ { } ] [ 1array ] if-void ]
62 : function-quot ( return library function types -- quot )
63 '[ _ _ _ _ alien-invoke ] ;
65 :: make-function ( return! library function! parameters -- word quot effect )
66 return function normalize-c-arg function! return!
67 function create-in dup reset-generic
68 return library function
69 parameters return parse-arglist [ function-quot ] dip ;
71 : parse-arg-tokens ( -- tokens )
72 ";" parse-tokens [ "()" subseq? not ] filter ;
74 : (FUNCTION:) ( -- word quot effect )
75 scan "c-library" get scan parse-arg-tokens make-function ;
77 : define-function ( return library function parameters -- )
78 make-function define-declared ;
80 : callback-quot ( return types abi -- quot )
81 [ [ ] 3curry dip alien-callback ] 3curry ;
83 : library-abi ( lib -- abi )
84 library [ abi>> ] [ "cdecl" ] if* ;
86 :: make-callback-type ( lib return! type-name! parameters -- word quot effect )
87 return type-name normalize-c-arg type-name! return!
88 type-name current-vocab create :> type-word
89 type-word [ reset-generic ] [ reset-c-type ] bi
90 void* type-word typedef
91 parameters return parse-arglist :> callback-effect :> types
92 type-word callback-effect "callback-effect" set-word-prop
93 type-word lib "callback-library" set-word-prop
94 type-word return types lib library-abi callback-quot (( quot -- alien )) ;
96 : (CALLBACK:) ( -- word quot effect )
98 scan scan parse-arg-tokens make-callback-type ;
100 PREDICATE: alien-function-word < word
103 [ last \ alien-invoke eq? ]
106 PREDICATE: alien-callback-type-word < typedef-word
107 "callback-effect" word-prop ;