1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: fry vectors sequences assocs math math.order accessors kernel
4 combinators quotations namespaces grouping stack-checker.state
5 stack-checker.backend stack-checker.errors stack-checker.visitor
6 stack-checker.values stack-checker.recursive-state ;
7 IN: stack-checker.branches
9 : balanced? ( pairs -- ? )
10 [ second ] filter [ first2 length - ] map all-equal? ;
12 SYMBOLS: +bottom+ +top+ ;
14 : unify-inputs ( max-input-count input-count meta-d -- new-meta-d )
15 ! Introduced values can be anything, and don't unify with
17 dup [ [ - +top+ <repetition> ] dip append ] [ 3drop f ] if ;
19 : pad-with-bottom ( seq -- newseq )
20 ! Terminated branches are padded with bottom values which
21 ! unify with literals.
23 dup [ length ] [ max ] map-reduce
24 '[ _ +bottom+ pad-head ] map
27 : phi-inputs ( max-input-count pairs -- newseq )
29 swap '[ [ _ ] dip first2 unify-inputs ] map
33 : remove-bottom ( seq -- seq' )
34 +bottom+ swap remove ;
36 : unify-values ( values -- phi-out )
39 [ known ] map dup all-eq?
40 [ first make-known ] [ drop <value> ] if
43 : phi-outputs ( phi-in -- stack )
44 flip [ unify-values ] map ;
48 : unify-branches ( ins stacks -- in phi-in phi-out )
50 [ keys supremum ] [ ] [ balanced? ] tri
51 [ dupd phi-inputs dup phi-outputs ]
52 [ quotations get unbalanced-branches-error ]
56 : branch-variable ( seq symbol -- seq )
57 '[ [ _ ] dip at ] map ;
59 : active-variable ( seq symbol -- seq )
60 [ [ terminated? over at [ drop f ] when ] map ] dip
63 : datastack-phi ( seq -- phi-in phi-out )
64 [ input-count branch-variable ] [ \ meta-d active-variable ] bi
66 [ input-count set ] [ ] [ dup >vector \ meta-d set ] tri* ;
68 : terminated-phi ( seq -- terminated )
69 terminated? branch-variable ;
71 : terminate-branches ( seq -- )
72 [ terminated? swap at ] all? [ terminate ] when ;
74 : compute-phi-function ( seq -- )
75 [ quotation active-variable sift quotations set ]
76 [ [ datastack-phi ] [ terminated-phi ] bi #phi, ]
77 [ terminate-branches ]
80 : copy-inference ( -- )
81 \ meta-d [ clone ] change
82 literals [ clone ] change
83 input-count [ ] change ;
85 GENERIC: infer-branch ( literal -- namespace )
87 M: literal infer-branch
91 [ value>> quotation set ] [ infer-literal-quot ] bi
94 M: callable infer-branch
98 [ quotation set ] [ infer-quot-here ] bi
101 : infer-branches ( branches -- input children data )
104 [ stack-visitor branch-variable ] keep ; inline
106 : (infer-if) ( branches -- )
108 [ first2 #if, ] dip compute-phi-function ;
111 2 literals-available? [
115 dup [ known [ curried? ] [ composed? ] bi or ] any? [
117 [ rot [ drop call ] [ nip call ] if ]
120 [ #drop, ] [ [ literal ] map (infer-if) ] bi
124 : infer-dispatch ( -- )
125 pop-literal nip infer-branches
126 [ #dispatch, ] dip compute-phi-function ;