1 ! Copyright (C) 2009 Jeremy Hughes.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.c-types assocs combinators.short-circuit
4 continuations effects fry kernel math memoize sequences
5 splitting strings peg.ebnf make ;
8 : cify-type ( str -- str' )
9 { { CHAR: - CHAR: space } } substitute ;
11 : factorize-type ( str -- str' )
14 "unsigned " ?head [ "u" prepend ] when
15 "long " ?head [ "long" prepend ] when
18 : const-pointer? ( str -- ? )
19 cify-type { [ " const" tail? ] [ "&" tail? ] } 1|| ;
21 : pointer-to-const? ( str -- ? )
22 cify-type "const " head? ;
24 : template-class? ( str -- ? )
27 MEMO: resolved-primitives ( -- seq )
28 primitive-types [ resolve-typedef ] map ;
30 : primitive-type? ( type -- ? )
32 factorize-type resolve-typedef [ resolved-primitives ] dip
34 ] [ 2drop f ] recover ;
36 : pointer? ( type -- ? )
37 factorize-type [ "*" tail? ] [ "&" tail? ] bi or ;
39 : type-sans-pointer ( type -- type' )
40 factorize-type [ '[ _ = ] "*&" swap any? ] trim-tail ;
42 : pointer-to-primitive? ( type -- ? )
44 { [ pointer? ] [ type-sans-pointer primitive-type? ] } 1&& ;
46 : pointer-to-non-const-primitive? ( str -- ? )
48 [ pointer-to-const? not ]
49 [ factorize-type pointer-to-primitive? ]
52 : types-effect>params-return ( types effect -- params return )
54 [ nip out>> dup length 0 > [ first ] [ drop "void" ] if ]
57 : annotate-effect ( types effect -- types effect' )
58 [ in>> ] [ out>> ] bi [
60 [ over pointer-to-primitive? [ ">" prepend ] when ]
64 TUPLE: c++-type name params ptr ;
65 C: <c++-type> c++-type
67 EBNF: (parse-c++-type)
70 alphanum = [1-9a-zA-Z]
71 name = [_a-zA-Z] [_a-zA-Z1-9:]* => [[ first2 swap prefix >string ]]
72 ptr = [*&] => [[ empty? not ]]
74 param = "," " "* type " "* => [[ third ]]
76 params = "<" " "* type " "* param* ">" => [[ [ 4 swap nth ] [ third ] bi prefix ]]
78 type = name " "* params? " "* ptr? => [[ { 0 2 4 } [ swap nth ] with map first3 <c++-type> ]]
81 : parse-c++-type ( str -- c++-type )
82 factorize-type (parse-c++-type) ;
84 DEFER: c++-type>string
86 : params>string ( params -- str )
87 [ "<" % [ c++-type>string ] map "," join % ">" % ] "" make ;
89 : c++-type>string ( c++-type -- str )
92 [ params>> [ params>string % ] when* ]
93 [ ptr>> [ "*" % ] when ]
97 GENERIC: c++-type ( obj -- c++-type/f )
99 M: object c++-type drop f ;