1 ! Copyright (C) 2007, 2008 Slava Pestov, Eduardo Cavazos.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors kernel locals.rewrite.point-free
4 locals.rewrite.sugar locals.types macros.expander make
5 quotations sequences sets words ;
6 IN: locals.rewrite.closures
8 ! Step 2: identify free variables and make them into explicit
9 ! parameters of lambdas which are curried on
11 GENERIC: rewrite-closures* ( obj -- )
13 : (rewrite-closures) ( form -- form' )
14 [ [ rewrite-closures* ] each ] [ ] make ;
16 : rewrite-closures ( form -- form' )
17 expand-macros (rewrite-sugar) (rewrite-closures) point-free ;
19 GENERIC: defs-vars* ( seq form -- seq' )
21 : defs-vars ( form -- vars ) { } [ defs-vars* ] reduce prune ;
23 M: def defs-vars* local>> unquote suffix ;
25 M: quotation defs-vars* [ defs-vars* ] each ;
27 M: object defs-vars* drop ;
29 GENERIC: uses-vars* ( seq form -- seq' )
31 : uses-vars ( form -- vars ) { } [ uses-vars* ] reduce prune ;
33 M: local-writer uses-vars* "local-reader" word-prop suffix ;
35 M: lexical uses-vars* suffix ;
37 M: quote uses-vars* local>> uses-vars* ;
39 M: object uses-vars* drop ;
41 M: quotation uses-vars* [ uses-vars* ] each ;
43 : free-vars ( form -- seq )
44 [ uses-vars ] [ defs-vars ] bi diff ;
46 M: callable rewrite-closures*
47 #! Turn free variables into bound variables, curry them
49 dup free-vars [ <quote> ] map
51 [ var-defs prepend (rewrite-closures) point-free , ]
52 [ length \ curry <repetition> % ]
55 M: object rewrite-closures* , ;