]> gitweb.factorcode.org Git - factor.git/blob - basis/xml/utilities/utilities.factor
Merge branch 'master' into experimental
[factor.git] / basis / xml / utilities / utilities.factor
1 ! Copyright (C) 2005, 2009 Daniel Ehrenberg
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors kernel namespaces sequences words io assocs
4 quotations strings parser lexer arrays xml.data xml.writer debugger
5 splitting vectors sequences.deep combinators fry memoize ;
6 IN: xml.utilities
7
8 : children>string ( tag -- string )
9     children>> {
10         { [ dup empty? ] [ drop "" ] }
11         { [ dup [ string? not ] contains? ]
12           [ "XML tag unexpectedly contains non-text children" throw ] }
13         [ concat ]
14     } cond ;
15
16 : children-tags ( tag -- sequence )
17     children>> [ tag? ] filter ;
18
19 : first-child-tag ( tag -- tag )
20     children>> [ tag? ] find nip ;
21
22 : tag-named? ( name elem -- ? )
23     dup tag? [ names-match? ] [ 2drop f ] if ;
24
25 : tags@ ( tag name -- children name )
26     [ { } like ] dip assure-name ;
27
28 : deep-tag-named ( tag name/string -- matching-tag )
29     assure-name '[ _ swap tag-named? ] deep-find ;
30
31 : deep-tags-named ( tag name/string -- tags-seq )
32     tags@ '[ _ swap tag-named? ] deep-filter ;
33
34 : tag-named ( tag name/string -- matching-tag )
35     assure-name swap [ tag-named? ] with find nip ;
36
37 : tags-named ( tag name/string -- tags-seq )
38     tags@ swap [ tag-named? ] with filter ;
39
40 : tag-with-attr? ( elem attr-value attr-name -- ? )
41     rot dup tag? [ swap attr = ] [ 3drop f ] if ;
42
43 : tag-with-attr ( tag attr-value attr-name -- matching-tag )
44     assure-name '[ _ _ tag-with-attr? ] find nip ;
45
46 : tags-with-attr ( tag attr-value attr-name -- tags-seq )
47     tags@ '[ _ _ tag-with-attr? ] filter children>> ;
48
49 : deep-tag-with-attr ( tag attr-value attr-name -- matching-tag )
50     assure-name '[ _ _ tag-with-attr? ] deep-find ;
51
52 : deep-tags-with-attr ( tag attr-value attr-name -- tags-seq )
53     tags@ '[ _ _ tag-with-attr? ] deep-filter ;
54
55 : get-id ( tag id -- elem )
56     "id" deep-tag-with-attr ;
57
58 : deep-tags-named-with-attr ( tag tag-name attr-value attr-name -- tags )
59     [ deep-tags-named ] 2dip tags-with-attr ;
60
61 : assert-tag ( name name -- )
62     names-match? [ "Unexpected XML tag found" throw ] unless ;
63
64 : insert-children ( children tag -- )
65     dup children>> [ push-all ]
66     [ swap V{ } like >>children drop ] if ;
67
68 : insert-child ( child tag -- )
69     [ 1vector ] dip insert-children ;
70
71 : XML-NS:
72     CREATE-WORD (( string -- name )) over set-stack-effect
73     scan '[ f swap _ <name> ] define-memoized ; parsing