factor/library/alien/structs.factor

81 lines
2.4 KiB
Factor
Raw Normal View History

2005-04-09 18:30:46 -04:00
! Copyright (C) 2004, 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
IN: alien
2005-04-09 22:43:41 -04:00
USING: assembler compiler errors generic hashtables kernel lists
math namespaces parser strings words ;
2005-04-09 18:30:46 -04:00
! Some code for interfacing with C structures.
: define-getter ( offset type name -- )
#! Define a word with stack effect ( alien -- obj ) in the
#! current 'in' vocabulary.
create-in >r
[ "getter" get ] bind cons r> swap define-compound ;
: define-setter ( offset type name -- )
#! Define a word with stack effect ( obj alien -- ) in the
#! current 'in' vocabulary.
"set-" swap cat2 create-in >r
[ "setter" get ] bind cons r> swap define-compound ;
: define-field ( offset type name -- offset )
>r c-type dup >r [ "align" get ] bind align r> r>
"struct-name" get swap "-" swap cat3
( offset type name -- )
3dup define-getter 3dup define-setter
drop [ "width" get ] bind + ;
: define-member ( max type -- max )
c-type [ "width" get ] bind max ;
2005-04-09 22:43:41 -04:00
: struct-constructor ( width -- )
2005-04-09 18:30:46 -04:00
#! Make a word <foo> where foo is the structure name that
#! allocates a Factor heap-local instance of this structure.
#! Used for C functions that expect you to pass in a struct.
2005-04-09 22:43:41 -04:00
"struct-name" get constructor-word
swap [ <byte-array> ] cons
define-compound ;
: array-constructor ( width -- )
#! Make a word <foo-array> ( n -- byte-array ).
"struct-name" get "-array" cat2 constructor-word
swap [ * <byte-array> ] cons
define-compound ;
: define-nth ( width -- )
#! Make a word foo-nth ( n alien -- dsplaced-alien ).
"struct-name" get "-nth" cat2 create-in
swap [ swap >r * r> <displaced-alien> ] cons
2005-04-09 18:30:46 -04:00
define-compound ;
: define-struct-type ( width -- )
#! Define inline and pointer type for the struct. Pointer
#! type is exactly like void*.
2005-04-09 22:43:41 -04:00
dup struct-constructor
dup array-constructor
dup define-nth
2005-04-16 00:23:27 -04:00
[
"width" set
[ swap <displaced-alien> ] "getter" set
] "struct-name" get define-c-type
2005-04-09 18:30:46 -04:00
"void*" c-type "struct-name" get "*" cat2
c-types get set-hash ;
: BEGIN-STRUCT: ( -- offset )
scan "struct-name" set 0 ; parsing
: FIELD: ( offset -- offset )
scan scan define-field ; parsing
: END-STRUCT ( length -- )
2005-04-09 22:43:41 -04:00
define-struct-type ; parsing
2005-04-09 18:30:46 -04:00
: BEGIN-UNION: ( -- max )
scan "struct-name" set 0 ; parsing
: MEMBER: ( max -- max )
scan define-member ; parsing
: END-UNION ( max -- )
2005-04-09 22:43:41 -04:00
define-struct-type ; parsing