factor/extra/xml/data/data.factor

106 lines
2.5 KiB
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
! Copyright (C) 2005, 2006 Daniel Ehrenberg
! See http://factorcode.org/license.txt for BSD license.
USING: kernel sequences sequences.private assocs arrays delegate vectors ;
2007-09-20 18:09:08 -04:00
IN: xml.data
TUPLE: name space tag url ;
C: <name> name
: ?= ( object/f object/f -- ? )
2dup and [ = ] [ 2drop t ] if ;
: names-match? ( name1 name2 -- ? )
[ name-space swap name-space ?= ] 2keep
[ name-url swap name-url ?= ] 2keep
name-tag swap name-tag ?= and and ;
: <name-tag> ( string -- name )
f swap f <name> ;
: assure-name ( string/name -- name )
dup name? [ <name-tag> ] unless ;
TUPLE: opener name attrs ;
C: <opener> opener
TUPLE: closer name ;
C: <closer> closer
TUPLE: contained name attrs ;
C: <contained> contained
TUPLE: comment text ;
C: <comment> comment
TUPLE: directive text ;
C: <directive> directive
TUPLE: instruction text ;
C: <instruction> instruction
TUPLE: prolog version encoding standalone ;
C: <prolog> prolog
TUPLE: xml prolog before after ;
: <xml> ( prolog before main after -- xml )
{ set-xml-prolog set-xml-before set-delegate set-xml-after }
xml construct ;
TUPLE: attrs ;
: <attrs> ( alist -- attrs )
attrs construct-delegate ;
: attr@ ( key alist -- index {key,value} )
>r assure-name r>
[ first names-match? ] curry* find ;
M: attrs at*
attr@ nip [ second t ] [ f f ] if* ;
M: attrs set-at
2dup attr@ nip [
2nip set-second
] [
2007-12-17 15:29:21 -05:00
[ >r assure-name swap 2array r> ?push ] keep
set-delegate
2007-09-20 18:09:08 -04:00
] if* ;
M: attrs assoc-size length ;
M: attrs new-assoc drop V{ } new <attrs> ;
2007-11-26 18:20:10 -05:00
M: attrs >alist delegate >alist ;
2007-09-20 18:09:08 -04:00
: >attrs ( assoc -- attrs )
2007-12-17 15:29:21 -05:00
dup [
V{ } assoc-clone-like
[ >r assure-name r> ] assoc-map
] when <attrs> ;
2007-09-20 18:09:08 -04:00
M: attrs assoc-like
drop dup attrs? [ >attrs ] unless ;
M: attrs clear-assoc
2007-12-17 15:29:21 -05:00
f swap set-delegate ;
2007-09-20 18:09:08 -04:00
M: attrs delete-at
tuck attr@ drop [ swap delete-nth ] [ drop ] if* ;
INSTANCE: attrs assoc
TUPLE: tag attrs children ;
: <tag> ( name attrs children -- tag )
>r >r assure-name r> T{ attrs } assoc-like r>
{ set-delegate set-tag-attrs set-tag-children }
tag construct ;
! For convenience, tags follow the assoc protocol too (for attrs)
CONSULT: assoc-protocol tag tag-attrs ;
2007-09-20 18:09:08 -04:00
INSTANCE: tag assoc
! They also follow the sequence protocol (for children)
CONSULT: sequence-protocol tag tag-children ;
2007-09-20 18:09:08 -04:00
INSTANCE: tag sequence
! tag with children=f is contained
: <contained-tag> ( name attrs -- tag )
f <tag> ;
PREDICATE: tag contained-tag tag-children not ;
PREDICATE: tag open-tag tag-children ;