factor/basis/macros/expander/expander.factor

95 lines
2.2 KiB
Factor
Raw Normal View History

! Copyright (C) 2008, 2009 Slava Pestov.
2008-08-24 04:59:37 -04:00
! See http://factorcode.org/license.txt for BSD license.
2014-12-16 14:09:47 -05:00
USING: accessors arrays combinators combinators.short-circuit
continuations effects fry generalizations kernel make math
namespaces quotations sequences sequences.private vectors words
;
2008-08-24 04:59:37 -04:00
IN: macros.expander
GENERIC: expand-macros ( quot -- quot' )
SYMBOL: stack
2014-12-16 14:09:47 -05:00
: begin ( -- )
V{ } clone stack set ;
2008-08-24 04:59:37 -04:00
: end ( -- )
2014-12-16 14:09:47 -05:00
stack get [ [ literalize , ] each ] [ delete-all ] bi ;
2008-08-24 04:59:37 -04:00
GENERIC: condomize? ( obj -- ? )
M: array condomize? [ condomize? ] any? ;
M: callable condomize? [ condomize? ] any? ;
M: object condomize? drop f ;
GENERIC: condomize ( obj -- obj' )
M: array condomize [ condomize ] map ;
M: callable condomize [ condomize ] map ;
M: object condomize ;
2014-12-16 14:09:47 -05:00
: literal ( obj -- )
dup condomize? [ condomize ] when stack get push ;
2008-08-24 04:59:37 -04:00
GENERIC: expand-macros* ( obj -- )
M: wrapper expand-macros* wrapped>> literal ;
2008-10-17 17:54:07 -04:00
: expand-dispatch? ( word -- ? )
\ dispatch eq? stack get length 1 >= and ;
: expand-dispatch ( -- )
stack get pop end
[ [ expand-macros ] [ ] map-as '[ _ dip ] % ]
[
2010-01-14 10:10:13 -05:00
length iota [ <reversed> ] keep
2008-10-17 17:54:07 -04:00
[ '[ _ ndrop _ nnip call ] [ ] like ] 2map , \ dispatch ,
] bi ;
: word, ( word -- ) end , ;
: expand-macro ( word quot -- )
'[
drop
stack [ _ with-datastack >vector ] change
2014-12-16 14:09:47 -05:00
stack get pop >quotation end
[ expand-macros* ] each
] [
drop
word,
] recover ;
2008-08-24 04:59:37 -04:00
2014-12-16 14:09:47 -05:00
: macro-quot ( word -- quot/f )
{
[ "transform-quot" word-prop ]
[ "macro" word-prop ]
} 1|| ;
: macro-effect ( word -- n )
{
[ "transform-n" word-prop ]
[ stack-effect in>> length ]
} 1|| ;
2008-08-24 04:59:37 -04:00
: expand-macro? ( word -- quot ? )
2014-12-16 14:09:47 -05:00
dup macro-quot [
swap macro-effect stack get length <=
] [
drop f f
] if* ;
2008-08-24 04:59:37 -04:00
M: word expand-macros*
2014-12-16 14:09:47 -05:00
{
{ [ dup expand-dispatch? ] [ drop expand-dispatch ] }
{ [ dup expand-macro? ] [ expand-macro ] }
[ drop word, ]
} cond ;
2008-08-24 04:59:37 -04:00
M: object expand-macros* literal ;
M: callable expand-macros*
expand-macros literal ;
M: callable expand-macros ( quot -- quot' )
2014-12-16 14:09:47 -05:00
[ begin [ expand-macros* ] each end ] [ ] make ;