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 arrays assocs classes
4 combinators combinators.short-circuit compiler.units effects
5 grouping kernel parser sequences splitting words fry locals
6 lexer namespaces summary math vocabs.parser ;
9 : parse-c-type-name ( name -- word )
10 dup search [ nip ] [ no-word ] if* ;
12 : parse-c-type ( string -- array )
14 { [ dup "void" = ] [ drop void ] }
15 { [ CHAR: ] over member? ] [ parse-array-type parse-c-type-name prefix ] }
16 { [ dup search c-type-word? ] [ parse-c-type-name ] }
17 { [ "**" ?tail ] [ drop void* ] }
18 { [ "*" ?tail ] [ parse-c-type-name resolve-pointer-type ] }
19 [ parse-c-type-name no-c-type ]
22 : scan-c-type ( -- c-type )
24 [ drop \ } parse-until >array ]
27 : reset-c-type ( word -- )
28 dup "struct-size" word-prop
29 [ dup [ forget-class ] [ { "struct-size" } reset-props ] bi ] when
30 { "c-type" "pointer-c-type" "callback-effect" "callback-abi" } reset-props ;
32 : CREATE-C-TYPE ( -- word )
33 scan current-vocab create {
40 : normalize-c-arg ( type name -- type' name' )
43 [ CHAR: * = ] trim-head
44 [ length - CHAR: * <array> append ] keep
46 [ parse-c-type ] dip ;
48 : parse-arglist ( parameters return -- types effect )
50 2 group [ first2 normalize-c-arg 2array ] map
51 unzip [ "," ?tail drop ] map
53 [ [ { } ] [ 1array ] if-void ]
56 : function-quot ( return library function types -- quot )
57 '[ _ _ _ _ alien-invoke ] ;
59 :: make-function ( return! library function! parameters -- word quot effect )
60 return function normalize-c-arg function! return!
61 function create-in dup reset-generic
62 return library function
63 parameters return parse-arglist [ function-quot ] dip ;
65 : parse-arg-tokens ( -- tokens )
66 ";" parse-tokens [ "()" subseq? not ] filter ;
68 : (FUNCTION:) ( -- word quot effect )
69 scan "c-library" get scan parse-arg-tokens make-function ;
71 : define-function ( return library function parameters -- )
72 make-function define-declared ;
74 : callback-quot ( return types abi -- quot )
75 [ [ ] 3curry dip alien-callback ] 3curry ;
77 :: make-callback-type ( abi return! type-name! parameters -- word quot effect )
78 return type-name normalize-c-arg type-name! return!
79 type-name current-vocab create :> type-word
80 type-word [ reset-generic ] [ reset-c-type ] bi
81 void* type-word typedef
82 parameters return parse-arglist :> callback-effect :> types
83 type-word callback-effect "callback-effect" set-word-prop
84 type-word abi "callback-abi" set-word-prop
85 type-word return types abi callback-quot (( quot -- alien )) ;
87 : (CALLBACK:) ( abi -- word quot effect )
88 scan scan parse-arg-tokens make-callback-type ;
90 PREDICATE: alien-function-word < word
93 [ last \ alien-invoke eq? ]
96 PREDICATE: alien-callback-type-word < typedef-word
97 "callback-effect" word-prop ;