1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays hashtables html.parser.state
4 html.parser.utils kernel namespaces sequences
5 unicode.case unicode.categories combinators.short-circuit
9 TUPLE: tag name attributes text closing? ;
19 : closing-tag? ( string -- ? )
21 [ { [ first CHAR: / = ] [ peek CHAR: / = ] } 1|| ] if-empty ;
23 : <tag> ( name attributes closing? -- tag )
29 : make-tag ( string attribs -- tag )
30 [ [ closing-tag? ] keep "/" trim1 ] dip rot <tag> ;
32 : new-tag ( text name -- tag )
37 : (read-quote) ( state-parser ch -- string )
38 '[ [ current _ = ] take-until ] [ next drop ] bi ;
40 : read-single-quote ( state-parser -- string )
41 CHAR: ' (read-quote) ;
43 : read-double-quote ( state-parser -- string )
44 CHAR: " (read-quote) ;
46 : read-quote ( state-parser -- string )
47 dup get+increment CHAR: ' =
48 [ read-single-quote ] [ read-double-quote ] if ;
50 : read-key ( state-parser -- string )
52 [ current { [ CHAR: = = ] [ blank? ] } 1|| ] take-until ;
54 : read-token ( state-parser -- string )
55 [ current blank? ] take-until ;
57 : read-value ( state-parser -- string )
59 dup current quote? [ read-quote ] [ read-token ] if
62 : read-comment ( state-parser -- )
63 "-->" take-until-sequence comment new-tag push-tag ;
65 : read-dtd ( state-parser -- )
66 ">" take-until-sequence dtd new-tag push-tag ;
68 : read-bang ( state-parser -- )
69 next dup { [ current CHAR: - = ] [ peek-next CHAR: - = ] } 1&&
70 [ next next read-comment ] [ read-dtd ] if ;
72 : read-tag ( state-parser -- string )
73 [ [ current "><" member? ] take-until ]
74 [ dup current CHAR: < = [ next ] unless drop ] bi ;
76 : read-until-< ( state-parser -- string )
77 [ current CHAR: < = ] take-until ;
79 : parse-text ( state-parser -- )
80 read-until-< [ text new-tag push-tag ] unless-empty ;
82 : parse-key/value ( state-parser -- key value )
84 [ skip-whitespace "=" take-sequence ]
85 [ swap [ read-value ] [ drop f ] if ] tri ;
87 : (parse-attributes) ( state-parser -- )
89 dup state-parse-end? [
92 [ parse-key/value swap set ] [ (parse-attributes) ] bi
95 : parse-attributes ( state-parser -- hashtable )
96 [ (parse-attributes) ] H{ } make-assoc ;
98 : (parse-tag) ( string -- string' hashtable )
100 [ read-token >lower ] [ parse-attributes ] bi
103 : read-< ( state-parser -- string/f )
105 CHAR: ! = [ read-bang f ] [ read-tag ] if
110 : parse-tag ( state-parser -- )
111 read-< [ (parse-tag) make-tag push-tag ] unless-empty ;
113 : (parse-html) ( state-parser -- )
115 [ parse-text ] [ parse-tag ] [ (parse-html) ] tri
118 : tag-parse ( quot -- vector )
119 V{ } clone tagstack [ state-parse ] with-variable ; inline
121 : parse-html ( string -- vector )
122 [ (parse-html) tagstack get ] tag-parse ;