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 ;
8 : children>string ( tag -- string )
10 { [ dup empty? ] [ drop "" ] }
11 { [ dup [ string? not ] contains? ]
12 [ "XML tag unexpectedly contains non-text children" throw ] }
16 : children-tags ( tag -- sequence )
17 children>> [ tag? ] filter ;
19 : first-child-tag ( tag -- tag )
20 children>> [ tag? ] find nip ;
22 : tag-named? ( name elem -- ? )
23 dup tag? [ names-match? ] [ 2drop f ] if ;
25 : tags@ ( tag name -- children name )
26 [ { } like ] dip assure-name ;
28 : deep-tag-named ( tag name/string -- matching-tag )
29 assure-name '[ _ swap tag-named? ] deep-find ;
31 : deep-tags-named ( tag name/string -- tags-seq )
32 tags@ '[ _ swap tag-named? ] deep-filter ;
34 : tag-named ( tag name/string -- matching-tag )
35 assure-name swap [ tag-named? ] with find nip ;
37 : tags-named ( tag name/string -- tags-seq )
38 tags@ swap [ tag-named? ] with filter ;
40 : tag-with-attr? ( elem attr-value attr-name -- ? )
41 rot dup tag? [ swap attr = ] [ 3drop f ] if ;
43 : tag-with-attr ( tag attr-value attr-name -- matching-tag )
44 assure-name '[ _ _ tag-with-attr? ] find nip ;
46 : tags-with-attr ( tag attr-value attr-name -- tags-seq )
47 tags@ '[ _ _ tag-with-attr? ] filter children>> ;
49 : deep-tag-with-attr ( tag attr-value attr-name -- matching-tag )
50 assure-name '[ _ _ tag-with-attr? ] deep-find ;
52 : deep-tags-with-attr ( tag attr-value attr-name -- tags-seq )
53 tags@ '[ _ _ tag-with-attr? ] deep-filter ;
55 : get-id ( tag id -- elem )
56 "id" deep-tag-with-attr ;
58 : deep-tags-named-with-attr ( tag tag-name attr-value attr-name -- tags )
59 [ deep-tags-named ] 2dip tags-with-attr ;
61 : assert-tag ( name name -- )
62 names-match? [ "Unexpected XML tag found" throw ] unless ;
64 : insert-children ( children tag -- )
65 dup children>> [ push-all ]
66 [ swap V{ } like >>children drop ] if ;
68 : insert-child ( child tag -- )
69 [ 1vector ] dip insert-children ;
72 CREATE-WORD (( string -- name )) over set-stack-effect
73 scan '[ f swap _ <name> ] define-memoized ; parsing