Revert "lists: Add list literal doc example."
[factor.git] / core / classes / union / union.factor
blob05bb9bee3d24f22d7d9eabc8b9eb44ffdaf77c86
1 ! Copyright (C) 2004, 2011 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors assocs classes classes.algebra
4 classes.algebra.private classes.builtin classes.private
5 combinators definitions kernel kernel.private math math.private
6 quotations sequences sets words ;
7 IN: classes.union
9 PREDICATE: union-class < class
10     "metaclass" word-prop union-class eq? ;
12 <PRIVATE
14 GENERIC: union-of-builtins? ( class -- ? )
16 M: builtin-class union-of-builtins? drop t ;
18 M: union-class union-of-builtins?
19     class-members [ union-of-builtins? ] all? ;
21 M: class union-of-builtins?
22     drop f ;
24 : fast-union-mask ( class -- n )
25     [ 0 ] dip flatten-class
26     [ drop class>type 2^ bitor ] assoc-each ;
28 : empty-union-predicate-quot ( class -- quot )
29     drop [ drop f ] ;
31 : fast-union-predicate-quot ( class -- quot )
32     fast-union-mask 1quotation
33     [ tag 1 swap fixnum-shift-fast ]
34     [ fixnum-bitand 0 eq? not ]
35     surround ;
37 : slow-union-predicate-quot ( class -- quot )
38     class-members [ predicate-def ] map unclip swap
39     [ [ dup ] prepend [ drop t ] ] { } map>assoc alist>quot ;
41 : union-predicate-quot ( class -- quot )
42     {
43         { [ dup class-members empty? ] [ empty-union-predicate-quot ] }
44         { [ dup union-of-builtins? ] [ fast-union-predicate-quot ] }
45         [ slow-union-predicate-quot ]
46     } cond ;
48 : define-union-predicate ( class -- )
49     dup union-predicate-quot define-predicate ;
51 M: union-class update-class define-union-predicate ;
53 ERROR: cannot-reference-self class members ;
55 : check-self-reference ( class members -- class members )
56     2dup all-contained-classes member-eq? [ cannot-reference-self ] when ;
58 : (define-union-class) ( class members -- )
59     check-self-reference f swap f union-class make-class-props (define-class) ;
61 PRIVATE>
63 : define-union-class ( class members -- )
64     [ (define-union-class) ]
65     [ drop changed-conditionally ]
66     [ drop update-classes ]
67     2tri ;
69 M: union-class rank-class drop 7 ;
71 M: union-class instance?
72     "members" word-prop [ instance? ] with any? ;
74 M: anonymous-union instance?
75     members>> [ instance? ] with any? ;
77 M: anonymous-union class-name
78     members>> [ class-name ] map " " join ;
80 M: union-class normalize-class
81     class-members <anonymous-union> normalize-class ;
83 M: union-class (flatten-class)
84     class-members <anonymous-union> (flatten-class) ;