1 ! Copyright (C) 2011 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: assocs combinators combinators.short-circuit formatting
5 grouping hashtables io kernel make math math.parser sequences
6 splitting strings unicode.categories ;
12 : decode-value ( string -- string' )
16 [ CHAR: \ = not ] [ CHAR: ` = ] bi* and ;
18 : (find-`) ( string -- n/f )
19 2 clump [ first2 `? ] find drop [ 1 + ] [ f ] if* ;
21 : find-` ( string -- n/f )
22 dup ?first CHAR: ` = [ drop 0 ] [ (find-`) ] if ;
24 : parse-name ( string -- remain name )
25 ":`" split1 swap decode-value ;
29 : (parse-value) ( string -- values )
30 decode-value string-lines dup length 1 = [ first ] when ;
32 : parse-value ( string -- remain value )
34 dup 1 - pick ?nth CHAR: : =
35 [ drop name/values ] [ cut swap (parse-value) ] if
36 [ rest [ blank? ] trim-head ] dip
39 : (name=value) ( string -- remain term )
40 parse-name [ parse-value ] dip associate ;
42 : name=value ( string -- remain term )
44 ":`" over subseq? [ (name=value) ] [ f swap ] if ;
46 : name/values ( string -- remain terms )
47 [ dup { [ empty? not ] [ first CHAR: ` = not ] } 1&& ]
48 [ name=value ] produce assoc-combine ;
50 : parse-txon ( string -- objects )
51 [ dup empty? not ] [ name=value ] produce nip ;
55 : txon> ( string -- object )
56 parse-txon dup length 1 = [ first ] when ;
60 : encode-value ( string -- string' )
65 GENERIC: >txon ( object -- string )
68 [ >txon ] map "\n" join ;
72 first2 [ encode-value ] [ >txon ] bi* "%s:`%s`" sprintf